array push php associative array code example

Example 1: php append to array

$myArr = [1, 2, 3, 4];

array_push($myArr, 5, 8);
print_r($myArr); // [1, 2, 3, 4, 5, 8]

$myArr[] = -1;
print_r($myArr); // [1, 2, 3, 4, 5, 8, -1]

Example 2: php append element to array

array_push($cart, 13);

Example 3: php add to associative array

// for php 5.4+
$data += [$key => $value];

// for php 5.4-
$data += array($key => $value);

Example 4: php add to existing associative array

$a1=['aa'=>'123' , 'bb'=>'454'];

$a1 = array_merge( $a1 , ['a'=>1,'b'=>2] ) ;

Example 5: php add new item to associative array

$a = array('foo' => 'bar'); // when you create
$a['Title'] = 'blah'; // later

Example 6: php array push key value

<?php
$image[0] = $image[0].','.$filename;
?>