Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Push item to associative array in PHP

Tags:

arrays

php

I've been trying to push an item to an associative array like this:

$new_input['name'] = array(     'type' => 'text',      'label' => 'First name',      'show' => true,      'required' => true ); array_push($options['inputs'], $new_input); 

However, instead of 'name' as the key in adds a number. Is there another way to do it?

like image 931
ryudice Avatar asked Jul 08 '10 16:07

ryudice


People also ask

What is Array_push in PHP?

Definition and Usage. The array_push() function inserts one or more elements to the end of an array. Tip: You can add one value, or as many as you like. Note: Even if your array has string keys, your added elements will always have numeric keys (See example below).

How can I append an array to another array in PHP?

Given two array arr1 and arr2 and the task is to append one array to another array. Using array_merge function: This function returns a new array after merging the two arrays. $arr1 = array ( "Geeks" , "g4g" );

What is an associative array give an example in PHP?

Associative arrays are used to store key value pairs. For example, to store the marks of different subject of a student in an array, a numerically indexed array would not be the best choice.


2 Answers

$options['inputs']['name'] = $new_input['name']; 
like image 175
webbiedave Avatar answered Sep 26 '22 01:09

webbiedave


Instead of array_push(), use array_merge()

It will merge two arrays and combine their items in a single array.

Example Code -

$existing_array = array('a'=>'b', 'b'=>'c'); $new_array = array('d'=>'e', 'f'=>'g');  $final_array=array_merge($existing_array, $new_array); 

Its returns the resulting array in the final_array. And results of resulting array will be -

array('a'=>'b', 'b'=>'c','d'=>'e', 'f'=>'g') 

Please review this link, to be aware of possible problems.

like image 38
Murtaza Khursheed Hussain Avatar answered Sep 26 '22 01:09

Murtaza Khursheed Hussain