Home >Backend Development >PHP Problem >How to add a value to a php array

How to add a value to a php array

青灯夜游
青灯夜游Original
2022-06-02 20:45:465430browse

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.

How to add a value to a php array

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, &#39;cherry&#39;);

echo "增加后的数组:" ;
var_dump($arr);
?>

How to add a value to a php array

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, &#39;cherry&#39;);

echo "增加后的数组:" ;
var_dump($arr);
?>

How to add a value to a php array

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);
?>

How to add a value to a php array

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,&#39;pie&#39;); //在第三个元素后插入一个元素
var_dump($arr);
?>

How to add a value to a php array

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!

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