Home >Backend Development >PHP Tutorial >How to add elements to the head and tail of an array in PHP
For numerically indexed arrays, add elements to the array through the array_push() function.
The array_push() function treats the array as a stack and pushes the incoming variables into the end of the array. The length of the array will increase as the number of variables pushed into the stack increases, and returns the total number of new units in the array. .
Add elements at the end
The syntax format is as follows:
int array_push ( array &$array , mixed $var [, mixed $... ] )
The parameter array is the specified array, and the parameter $var is the pressure values in the array.
The following is the array_push() function to add elements to the end of the array. The specific example code is as follows:
<?php header("Content-Type:text/html; charset=utf-8"); $array_push = array("PHP中文网","百度一下");//定义数组 array_push($array_push,"搜狗浏览器","火狐浏览器");//添加元素 print_r($array_push);// 输出数组结果 ?>
The output result is:
Another simpler way to add array elements, for numeric subscript arrays:
$names[] = 'ruby';
The function is similar to array_push, but only one can be added at a time. Associative arrays can be Add key
$info['height'] = 1.7;
in brackets. Reference code
$names[] = 'lucy'; $names[] = 'lily'; // 等同于 array_push($names, 'lucy', 'lily');
array_unshift. Add element
array_push in the header. The principle is similar , just in different directions.
The syntax format is as follows:
int array_unshift ( array &$array , mixed $var [, mixed $... ] )
Below we will introduce the array_unshift() function directly through examples. The specific code is as follows:
<?php header("Content-Type:text/html; charset=utf-8"); $names = ['andy', 'tom', 'jack']; array_unshift($names, 'joe', 'hank'); print_r($names); ?>
The output result is:
In the next article we will introduce "How to delete the head, tail, and any element in a PHP array"!
【Related tutorial recommendations】
1. Relevant topic recommendations: "php array (Array)"
2. Related video course recommendations: "Using arrays to implement stack operations: array_push and array_pop"
The above is the detailed content of How to add elements to the head and tail of an array in PHP. For more information, please follow other related articles on the PHP Chinese website!