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?
in_array() function is utilized to determine if specific value exists in an array. It works fine for one dimensional numeric and associative arrays.
Use the array_push() Method to Insert Items to an Associative Array in PHP.
You can use any type with an associative array key or value that you can use with a scalar variable. You cannot nest an associative array within another associative array as a key or value. You can reference an associative array using any tuple that is compatible with the array key signature.
No, you cannot have multiple of the same key in an associative array. You could, however, have unique keys each of whose corresponding values are arrays, and those arrays have multiple elements for each key.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With