Methods for adding elements to the header and tail of the PHP array (array_unshift, array_push), arrayunshift
For a numeric index array, the array_push () function is used to add elements to the array.
The array_push () function regards the array as a stack and pushes the passed variables to the end of the array. The length of the array will increase as the number of incoming variables increases, returns the total number of new units in the array.
Add element 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 in the pressed array.
Below isarray_push()
The function adds an element to the end of the array. The sample code is as follows:
<? Phpheader ("Content-Type: text/html; charset = UTF-8"); $ array_push = array ("PHP 文",", ""); // define the array array_push ($ array_push, "sogou Browser", "FireFox Browser"); // Add the element print_r ($ array_push); // output the array result?>
Output result:
In addition, it is easier to add array elements. For numeric subscript Arrays:
$names[] = 'ruby';
The function is similar to that of array_push, but only one can be added at a time. The associated array can be added with the key in square brackets.
$info['height'] = 1.7;
Reference Code
$ Names [] = 'Lucy '; $ names [] = 'lily'; // equivalent to array_push ($ names, 'Lucy', 'lily ');
Add an element to the array_unshift Header
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 $...])
The following example describes the array_unshift () function. The Code is as follows:
<?phpheader("Content-Type:text/html; charset=utf-8");$names = ['andy', 'tom', 'jack'];array_unshift($names, 'joe', 'hank');print_r($names);?>
The output result is:
Next we will introduce how to delete the header, tail, and any element in the PHP array.
The above is how to add the element details to the header and tail of the PHP array. For more information, see other articles related to helping customers!