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:314813browse

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:

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[] = &#39;ruby&#39;;

The function is similar to array_push, but only one can be added at a time. Associative arrays can be Add key

$info[&#39;height&#39;] = 1.7;

in brackets. Reference code

$names[] = &#39;lucy&#39;;
$names[] = &#39;lily&#39;;
// 等同于
array_push($names, &#39;lucy&#39;, &#39;lily&#39;);

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 = [&#39;andy&#39;, &#39;tom&#39;, &#39;jack&#39;];
array_unshift($names, &#39;joe&#39;, &#39;hank&#39;);
print_r($names);
?>

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