Insert New Element Into Array


#1

Hello,

Whats the best way to insert a new element into a array? Can we use the hash function for that?

Example:

I have this array bellow and want to insert ID 4 into Product:

array(
	'Cart' => array(
		'id' => '1',
		'frete' => '15.00'
	),
	'Product' => array(
		'Product' => array(
			(int) 0 => '1',
			(int) 1 => '2',
			(int) 2 => '3'
		)
	)
)

Final result would be:

array(
	'Cart' => array(
		'id' => '1',
		'frete' => '15.00'
	),
	'Product' => array(
		'Product' => array(
			(int) 0 => '1',
			(int) 1 => '2',
			(int) 2 => '3'
			(int) 3 => '4'
		)
	)
)

#2

Assuming I am understanding correctly but you could use the push function.

http://php.net/manual/en/function.array-push.php


#3

Insert value into array PHP

PHP array_push() Function Main Tips

  1. The array_push() function inserts elements into the end of an array .
  2. You can as many values , as you like.
  3. Your added elements will always have numeric keys, even if your array has string keys.
  4. Returns the elements number in the array .
  5. Newly introduced in PHP4.