array_push for associative arrays

EnglishAdam picture EnglishAdam · Nov 27, 2011 · Viewed 85k times · Source

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?

Answer

akDeveloper picture akDeveloper · Nov 27, 2011

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.