2 of 110 menu

Adding an Element to a PHP Array

Using Square Brackets

The simplest way is by using square brackets. See the example:

<?php $arr = [1, 2, 3]; $arr[] = 4; $arr[] = 5; var_dump($arr); ?>

Code execution result:

[1, 2, 3, 4, 5]

Using array_push

To add a new element to the end of an array, you can use the function array_push. See the example:

<?php $arr = [1, 2, 3]; $arr = array_push($arr, 4, 5); var_dump($arr); ?>

Code execution result:

[1, 2, 3, 4, 5]

Using array_unshift

To add a new element to the beginning of an array, you can use the function array_unshift. See the example:

<?php $arr = [1, 2, 3]; $arr = array_unshift($arr, 4, 5); var_dump($arr); ?>

Code execution result:

[4, 5, 1, 2, 3]
English
БеларускаяEspañolРусский
We use cookies for website operation, analytics, and personalization. Data processing is carried out in accordance with the Privacy Policy.
accept all customize decline