Home > Article > Backend Development > Summary of methods for adding associated elements to PHP array_PHP tutorial
What we are introducing here is adding an associative array to an array. This synthesizes a multi-dimensional array. Let me give you a few examples. I hope it will be helpful to all classmates.
In the article "Summary of methods for adding elements to php arrays", we introduced how to add elements to an array. So what should I do if I want to add an element like $array=array('title'=>'php tutorial').
array_push, array_pop, array_shift, array_unshift These functions are all designed for numeric type index arrays.
To add an associative array, you can use the array_merge method or the + operator
Let’s first look at adding array elements to an array
1. How to add array elements in php:
(1) Add array elements through 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 returns false, where the variable can be multiple. All existing numeric keys will be modified accordingly, while associated keys are unaffected.
(4)array array_pad(array target_array,integer length,mixed pad_value) Increase the size of target_array to the length specified by length.
Is it okay to use array_push or array_unshift?
The answer is no
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
|
Copy code
|
||||||||
/* Array
|
[front] => hello
*/