0
$user = hobaa;
$usernames = array();
$usernames['name'] = $user;


print_r($usernames['name']);

Will issue something like

Array ( [name] => hobaa )

and print_r($usernames); will issue this out hobaa

How can I make it save multiple values?

Tried

$users = array("hobaa","test");
foreach($users as $user) {
    $usernames = array();
    $usernames['name'][] = $user;
   }
    print_r($usernames['name']);

But it just takes the last value.

Please help. Thanks!

2
  • 6
    Because you're resetting the array on every iteration $usernames = array();. Commented Aug 23, 2017 at 14:49
  • Thanks. Fixed and works fine! Commented Aug 23, 2017 at 14:51

3 Answers 3

1

From this code:

foreach($users as $user) {
    $usernames = array();
    $usernames['name'][] = $user;
   }

remove this line from loop:

$usernames = array();

and put it above the loop like:

$usernames = array();
foreach($users as $user) {
    $usernames['name'][] = $user;
   }

and try again. As you are re-initializing the array on every iteration.

Sign up to request clarification or add additional context in comments.

Comments

0

Something like:

$users = array("hobaa","test");
// a new usernames array to use
$usernames = array();
// 
foreach($users as $user) {
    array_push($usernames, $user);
}

print_r($usernames);

Will give:

Array ( [0] => hobaa [1] => test ) 

Comments

0

Define $usernamse variable outside of the loop. Use the following code :

$users = array("hobaa","test");
$usernames = array();
foreach($users as $user) {
    $usernames['name'][] = $user;
}
print_r($usernames['name']);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.