How to add elements in php: 1. Add array elements through assignment; 2. Add array elements through array_push function; 3. Add elements through array_unshift function; 4. Add elements through array_pad function.
The operating environment of this article: windows7 system, PHP7.4 version, DELL G3 computer
How to add elements to php?
1. How to add array elements in php:
(1) Add array elements by assignment: $states['name']='Tom';
(2)int array_push(array target_array,mixed variable [,mixed variable...]) The function adds the variable to the end of the target_array and returns true when successful, otherwise it returns false, where the variable can be multiple;
(3)int array_unshift(array target_array,mixed variable [,mixed variable...]) The function adds variable to the array head of target_array and returns true when successful, otherwise it returns false, where the variable can be multiple. All existing numerical keys will be modified accordingly, while associated keys will not be affected;
(4)array array_pad(array target_array,integer length,mixed pad_value) Increase the size of target_array to the length specified by length.
Specific method:
1. Use the array_merge method to implement a function similar to array_unshift that adds elements at the beginning
The code is as follows:
<?php $queue = array('a', 'B'); $queue = array_merge(array('front' => 'hello'), $queue); /* Array ( [front] => hello [0] => a [1] => b ) */ ?>
2. Operator
The code is as follows:
<?php $queue = array('a', 'B'); $queue = array('front' => 'Hello') + $queue; ?>
The output result is the same as using the array_merge method.
3. Add an associative array element at the end of the element
The code is as follows:
<?php $queue = array('a', 'B'); $queue['front'] = 'hello'; /* 输出 Array ( [0] => a [1] => b [front] => hello ) */ ?>
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of How to add elements in php. For more information, please follow other related articles on the PHP Chinese website!