1

print_r($members) coming like this following result

Array ( [myname] => Array ( [userid] => 52 [age] => 46 )
Array ( [hisname] => Array ( [userid] => 22 [age] => 47 )
Array ( [yourname] => Array ( [userid] => 47 [age] => 85 )

array_push() push not working in the foreach loop

foreach($members as $key => $item){
  // print "<br>" . $key ."<br>";
  array_push($members, '$key');
}

The result expecting like this following code with the array_push()

Array ( [myname] => Array ( [userid] => 52 [age] => 46 [0] => myname)
Array ( [hisname] => Array ( [userid] => 22 [age] => 47 [0] => hisname)
Array ( [yourname] => Array ( [userid] => 47 [age] => 85 [0] => yourname)

result

Warning: array_push() expects parameter 1 to be array, null given in C:\xampp\htdocs\index.php on line 126

Warning: array_push() expects parameter 1 to be array, null given in C:\xampp\htdocs\index.php on line 126

Warning: array_push() expects parameter 1 to be array, null given in C:\xampp\htdocs\index.php on line 126

5
  • And what is the output result? Ans what is $arr in your foreach? Commented May 22, 2014 at 9:59
  • That warning comes because you do not initialize $arr as an (empty) array. Place this before the loop: $arr=[];. No idea why that happens in all iterations though... Commented May 22, 2014 at 10:04
  • Oh, and: '$key' pushes the literal string "$key" onto the array, not the content of that variable. Commented May 22, 2014 at 10:06
  • Now you've changed the code in the question, and it seems that you are pushing data into $members, the same array which you are iterating. That seems like a bad idea. Commented May 22, 2014 at 10:10
  • @GolezTrol yes that is what I need to see in the end result. Create new array which should be the key. Hope you understand the question Commented May 22, 2014 at 10:13

1 Answer 1

5

Because $arr does not seems to be an array. Change your code to,

foreach($members as $key => $item){
   array_push($members[$key], $key); //or $members[$key][] = $key;
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.