3

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

Mo.
  • 26,306
  • 36
  • 159
  • 225
  • And what is the output result? Ans what is `$arr` in your foreach? – Gwenc37 May 22 '14 at 09: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... – arkascha May 22 '14 at 10:04
  • Oh, and: `'$key'` pushes the _literal_ string "$key" onto the array, not the _content_ of that variable. – arkascha May 22 '14 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. – GolezTrol May 22 '14 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 – Mo. May 22 '14 at 10:13

1 Answers1

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;
}
Rikesh
  • 26,156
  • 14
  • 79
  • 87