For numeric index arrays, add elements to the tail of the array through the array_push() function, and add elements to the head of the array_unshift. Friends in need can refer to the following
For numeric index arrays, use array_push( ) function adds elements to an array.
The array_push() function treats the array as a stack and pushes the incoming variables to the end of the array. The length of the array will increase as the number of variables pushed onto the stack increases, and the total number of new units in the array is returned.
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 value pushed into 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);// 输出数组结果 ?>
Output results For:
Another easier way to add array elements, for numeric subscripted arrays:
$names[] = 'ruby';
The function is similar to array_push, but only one can be added at a time. For associative arrays, you can add key in square brackets
$info['height'] = 1.7;
Reference code
$names[] = 'lucy'; $names[] = 'lily'; // 等同于 array_push($names, 'lucy', 'lily');
array_unshift adds elements to the head
The principle of array_push is similar, but the direction is different.
The syntax format is as follows:
int array_unshift ( array &$array , mixed $var [, mixed $... ] )
Let’s introduce it to you directly through examples. array_unshift() function, 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:
The above is The entire content of this article is hoped to be helpful to everyone's study.
Related recommendations:
PHP Two-dimensional array deduplication or statistics based on a certain field
PHP mkdir new folder permission problem
The above is the detailed content of PHP implements the method of adding elements to the head and tail of an array. For more information, please follow other related articles on the PHP Chinese website!