27

I'm trying to extend an assoc array like this, but PHP doesn't like it.

I receive this message:

Warning: array_push() expects parameter 1 to be array, null given

Here's my code:

$newArray = array();  
foreach ( $array as $key => $value ) { 
    $array[$key + ($value*100)] = $array[$key];
    unset ( $array[$key] );
    array_push ( $newArray [$key], $value );
}
//}
print_r($newArray);

Where did I go wrong?

Esailija
  • 138,174
  • 23
  • 272
  • 326
EnglishAdam
  • 1,380
  • 1
  • 19
  • 42
  • 2
    oh ok, sorry. Will do next time. After all it's in my interests too! Thanks. – EnglishAdam Nov 27 '11 at 21:46
  • that code looks really messy, would you tell us what you're trying to do? – Karoly Horvath Nov 27 '11 at 21:49
  • I had no luck with Ariz's method, I don't think it is correct. It created the index but would not set the value. See the answers below for the proper syntax of `$newArray[$key] = $value;` – drew010 Nov 27 '11 at 21:51
  • i'm trying to use array push but for an assoc array not a numeric array – EnglishAdam Nov 27 '11 at 21:55
  • php has assoc arrays. It has not numeric arrays like they defined in other languages. So even if you set up an array with only values, you also have indexes to. – akDeveloper Nov 27 '11 at 22:01

2 Answers2

58

This is your problem:

$newArray[$key] is null cause $newArray is an empty array and has not yet values.

You can replace your code, with

array_push( $newArray, $value );

or instead of array_push to use

$newArray[$key] = $value;

so you can keep the index of your $key.

akDeveloper
  • 1,048
  • 11
  • 11
  • Of course you are right! An assoc array doesn't rely on its numbering system so just adding another pair is the best way! Array push is more about giving the value a key. So it was a stupid question since assoc arrays already have a key!! Thanks for your time anyway! – EnglishAdam Nov 27 '11 at 22:06
  • 4
    The different is that `array_push()` always add an element to the bottom of an array while `$array[$key] = $value` may overwrite an element of your `$array`. – akDeveloper Dec 02 '11 at 07:42
9

I use array_merge prebuilt function for push in array as associative.

For example:-

$jsonDataArr=array('fname'=>'xyz','lname'=>'abc');
$pushArr=array("adm_no" => $adm_no,'date'=>$date);
$jsonDataArr = array_merge($jsonDataArr,$pushArr);
print_r($jsonDataArr);//Array ( [fname] => xyz [lname] => abc [adm_no] =>1234 [date] =>'2015-04-22')
vineet
  • 13,832
  • 10
  • 56
  • 76