EnglishAdam
EnglishAdam

Reputation: 1390

array_push for associative arrays

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?

Upvotes: 27

Views: 107029

Answers (2)

vineet
vineet

Reputation: 14236

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')

Upvotes: 9

akDeveloper
akDeveloper

Reputation: 1058

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.

Upvotes: 59

Related Questions