Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add values to an associative array in PHP

Tags:

php

I want to append an element to to end of an associative array.

For example, my array is

$test=Array ([chemical] => asdasd [chemical_hazards] => ggggg )  

and my result should be

$test=Array ([chemical] => asdasd [chemical_hazards] => ggggg [solution] => good)  

Could you tell me how to implement this?

like image 580
Thinker Avatar asked Dec 25 '09 07:12

Thinker


People also ask

How do you add the values at the end in the array in PHP?

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 do you code an associative array in PHP?

Associative array will have their index as string so that you can establish a strong association between key and values. The associative arrays have names keys that is assigned to them. $arr = array( "p"=>"150", "q"=>"100", "r"=>"120", "s"=>"110", "t"=>"115"); Above, we can see key and value pairs in the array.

What is an associative array PHP?

Associative Array - It refers to an array with strings as an index. Rather than storing element values in a strict linear index order, this stores them in combination with key values. Multiple indices are used to access values in a multidimensional array, which contains one or more arrays.


1 Answers

Just add it like you would with a non-associative array:

$test = array('chemical' => 'asdasd', 'chemical_hazards' => 'ggggg'); //init $test['solution'] = 'good'; 
like image 165
Sasha Chedygov Avatar answered Sep 18 '22 14:09

Sasha Chedygov