Search code examples
phparraysassociative-arrayarray-push

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?


Solution

  • 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.