In PHP, an array is a very useful data type that can store multiple values and can be accessed through subscripts. When we want to add a new value to an array, we can use some of the built-in functions of the array.
1. Use the array_push function
PHP provides a built-in function array_push() that can add one or more values to the end of the array.
The sample code is as follows:
<?php $arr = array(1, 2, 3, 4); $new_value = 5; array_push($arr, $new_value); print_r($arr); ?>
Run the above code, the output result is as follows:
Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 )
2. Use the "[]" operator
We can use The "[]" operator of an array adds a new value directly to the end of the array.
The sample code is as follows:
<?php $arr = array(1, 2, 3, 4); $new_value = 5; $arr[] = $new_value; print_r($arr); ?>
Run the above code, the output result is as follows:
Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 )
3. Use the array_unshift function
array_unshift() function can be used in the array Add one or more values to the beginning of .
The sample code is as follows:
<?php $arr = array(1, 2, 3, 4); $new_value = 0; array_unshift($arr, $new_value); print_r($arr); ?>
Run the above code, the output result is as follows:
Array ( [0] => 0 [1] => 1 [2] => 2 [3] => 3 [4] => 4 )
4. Use the " " operator
We can also use " ” operator to merge one array with another, in this operation the new value is added to the end of the original array.
The sample code is as follows:
<?php $arr = array(1, 2, 3, 4); $new_value = array(5); $result = $arr + $new_value; print_r($result); ?>
Run the above code, the output result is as follows:
Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 )
Summary:
The above is to add a value to the PHP array There are four methods, each method has its advantages and disadvantages, and we can choose the appropriate method according to the actual situation. Regardless of the method used, you should pay attention to the subscripts of the array to avoid errors.
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!