Home > Article > Backend Development > How to add key-value pairs to php array
How to add key-value pairs to a php array: 1. Use the "array_pad ($arr, $size, $value)" statement; 2. Use the "array_unshift ($arr, $value)" statement; 3. Use the "array_push($arr,$value)" statement.
The operating environment of this tutorial: windows7 system, PHP7.1 version, DELL G3 computer
php array add key Value pair
1. Use array_pad() function
array_pad() function can fill the array to the specified length with a certain value. The syntax is as follows:
array_pad ( $arr, $size , $value )
Parameter description:
Example:
<?php $arr = array(12, 10, 9); var_dump($arr); $result = array_pad($arr, 5, 0); //从数组右侧开始, 用0填补数组到含有5个元素 var_dump($result); $result = array_pad($arr, -7, -1); //从数组左侧开始, 用-1填补数组到含有7个元素 var_dump($result); $result = array_pad($arr, 2, "noop"); // 第二个参数小于数组长度, 不填补 var_dump($result); ?>
#2. Use array_unshift() function
array_unshift() function Used to insert one or more elements at the beginning of the array, the syntax is as follows:
array_unshift ( array &$arr , mixed $value1 [, mixed $value2, mixed $value3 ... ] )
Two points to note:
The elements are inserted as a whole , these elements will remain in the same order after insertion.
All numeric key names will be modified to start counting from 0, and all string key names will remain unchanged.
Example:
<?php header("Content-type:text/html;charset=utf-8"); $num = array(10, 45, 9); var_dump($num); array_unshift($num, 100, 6); //在数组开头插入元素 var_dump($num); ?>
##3. Use the array_push() function
array_push() function is used to insert one or more elements (push) at the end of the array. Its syntax is as follows:array_push ( array &$arr , mixed $value1 [, mixed $value2, mixed $value3 ... ] )Example:
<?php header("Content-type:text/html;charset=utf-8"); $num = array(10, 45, 9); var_dump($num); array_push($num, 100, 6); //在数组开头插入元素 var_dump($num); ?>Recommended learning: "
PHP Video Tutorial", "PHP ARRAY"
The above is the detailed content of How to add key-value pairs to php array. For more information, please follow other related articles on the PHP Chinese website!