Home >Backend Development >PHP Problem >How to add a value to a php array
Method: 1. Use "array_unshift(array, value)" to add the value at the beginning; 2. Use "array_push(array, value)" to add the value at the end; 3. Use "$array name[]= Value;" adds the value at the end; 4. Use "array_splice(array, position, 0, value)" to insert the value at the specified position.
The operating environment of this tutorial: Windows 7 system, PHP version 8.1, DELL G3 computer
Add to the php array 4 methods of a value
Method 1: Use array_unshift()
The array_unshift() function can insert a new value at the beginning of the array
<?php header("Content-type:text/html;charset=utf-8"); $arr=array(10,12,20,25,24); echo "原数组:"; var_dump($arr); array_unshift($arr, 'cherry'); echo "增加后的数组:" ; var_dump($arr); ?>
Note: array_unshift() function will change the original array
Method 2: Use array_push() function
array_push() function can insert a new value at the end of the array
<?php header("Content-type:text/html;charset=utf-8"); $arr=array(10,12,20,25,24); echo "原数组:"; var_dump($arr); array_push($arr, 'cherry'); echo "增加后的数组:" ; var_dump($arr); ?>
Note: array_push() function will also change the original array
method 3: Use $arr[]=value;
statement
This statement can add an element to the end of the array element
<?php header("Content-type:text/html;charset=utf-8"); $arr=array(10,12,20,25,24); echo "原数组:"; var_dump($arr); $arr[]=true; echo "增加后的数组:" ; var_dump($arr); ?>
Note: This method will also change the original array
Method 4: Use array_splice() function
array_splice() can be inserted at any position New element
<?php header("Content-type:text/html;charset=utf-8"); $arr=array(10,12,20,25,24); echo "原数组:"; var_dump($arr); echo "增加后的数组:" ; array_splice($arr,3,0,'pie'); //在第三个元素后插入一个元素 var_dump($arr); ?>
Note: The array_splice() function will also change the original array
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of How to add a value to a php array. For more information, please follow other related articles on the PHP Chinese website!