Jump to: navigation, search

Php array push

From w3cyberlearnings

Contents

PHP function array_push

This function inserts single or multiple elements to the end of an array.

Syntax array_push

  • array: array to add element to
  • element1: element 1
  • element2: element 2
array_push(array, element1, element2,...);

Example 1

<?php

$person = array('Kami'.'Kenji','Maiya','Hana');

array_push($person,'Aneko','Emma');

print_r($person);
?>

Output

Array
(
    [0] => KamiKenji
    [1] => Maiya
    [2] => Hana
    [3] => Aneko
    [4] => Emma
)

Example 2

<?php

$records = array('John', 'Zahra', 'Omari');
$keeps = array('Akira', 'Maiya', 'Akemi');

foreach ($records as $person) {
	if ($person == 'John') {
		array_push($keeps, $person);
	}
}

print_r($keeps);
?>

Output


Array
(
    [0] => Akira
    [1] => Maiya
    [2] => Akemi
    [3] => John
)

Example 3: for an associative array

<?php
$score = array('John'=>34,'Bob'=>32,'Vany'=>47);

$score['Mark'] = 37;

print_r($score);
?>

Output


Array
(
    [John] => 34
    [Bob] => 32
    [Vany] => 47
    [Mark] => 37
)

Related Links


Navigation
Web
SQL
MISC
References