Home >Backend Development >PHP Problem >How to dynamically add an array in php
In PHP programs, dynamically increasing arrays is a very common operation. In many scenarios, we need to dynamically increase arrays based on user input, database reading, and other operations. This article will introduce several methods to dynamically increase arrays in PHP.
Method 1: array_push()
PHP provides a built-in function array_push() that can add one or more values to the end of the array. It should be noted that array_push() will modify the original array and does not support chain operations.
Sample code:
$fruits = array('apple', 'banana'); array_push($fruits, 'orange', 'lemon'); print_r($fruits);
Output result:
Array ( [0] => apple [1] => banana [2] => orange [3] => lemon )
Method 2: $array[]
In PHP, you can also pass it directly to undefined The array index assignment method realizes dynamically increasing the array.
Sample code:
$fruits = array('apple', 'banana'); $fruits[] = 'orange'; // 等价于 array_push($fruits, 'orange'); $fruits[] = 'lemon'; // 等价于 array_push($fruits, 'lemon'); print_r($fruits);
Output result:
Array ( [0] => apple [1] => banana [2] => orange [3] => lemon )
Method three: array_merge()
array_merge() can merge one or more arrays into An array, the original array will not be modified, and chain operations are supported.
Sample code:
$fruits1 = array('apple', 'banana'); $fruits2 = array('orange', 'lemon'); $fruits = array_merge($fruits1, $fruits2); print_r($fruits);
Output result:
Array ( [0] => apple [1] => banana [2] => orange [3] => lemon )
Method 4: $array[key] = value
Also directly to an undefined array For index assignment, use the form $array[key] = value to add array elements.
Sample code:
$fruits = array('apple', 'banana'); $fruits[2] = 'orange'; $fruits[3] = 'lemon'; print_r($fruits);
Output result:
Array ( [0] => apple [1] => banana [2] => orange [3] => lemon )
Summary:
The above introduces several methods to dynamically increase arrays in PHP, among which array_push (), $array[] and array_merge() are commonly used methods, while $array[key] = value is more flexible and can add elements at any position. Choosing the appropriate method to operate according to the actual situation can make the code more concise and efficient.
The above is the detailed content of How to dynamically add an array in php. For more information, please follow other related articles on the PHP Chinese website!