Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

array_push for associative arrays

Tags:

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?

like image 677
EnglishAdam Avatar asked Nov 27 '11 21:11

EnglishAdam


People also ask

Does In_array work for associative array?

in_array() function is utilized to determine if specific value exists in an array. It works fine for one dimensional numeric and associative arrays.

How do you push data in an associative array?

Use the array_push() Method to Insert Items to an Associative Array in PHP.

What can be used in associative array?

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.

Can associative array have same key?

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.


1 Answers

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.

like image 50
akDeveloper Avatar answered Sep 19 '22 13:09

akDeveloper