Home>Article>Backend Development> How to add elements to the head and tail of an array in PHP

How to add elements to the head and tail of an array in PHP

黄舟
黄舟 Original
2017-05-04 11:45:31 4756browse

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 thearray_push() function to add elements to the end of the array. The specific example code is as follows:

The output result is:

How to add elements to the head and tail of an array in PHP

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:

The output result is:

How to add elements to the head and tail of an array in PHP

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn