In programming, it is often necessary to use arrays to store and manipulate data. Arrays in PHP are a very powerful data structure that can add, delete, and modify elements in the array through simple code. This article will introduce how to add elements to an array in PHP.
1. Use the array_push() function to add elements
The array_push() function can add one or more elements to the end of the array. The following is a sample code using the array_push() function:
<?php $arr1 = array("apple", "banana", "orange"); array_push($arr1, "grape","mango"); print_r($arr1); ?>
The output is as follows:
Array ( [0] => apple [1] => banana [2] => orange [3] => grape [4] => mango )
In the above sample code, we use the array_push() function to combine "grape" and "mango" Added to the end of array $arr1.
2. Use index to add elements
In addition to using the array_push() function, you can also use index to add elements. For example:
<?php $arr2 = array("apple", "banana", "orange"); $arr2[3] = "grape"; $arr2[4] = "mango"; print_r($arr2); ?>
The output is the same as the above example:
Array ( [0] => apple [1] => banana [2] => orange [3] => grape [4] => mango )
In the above example code, we added "grape" and "mango" to the end of the array $arr2 using index.
3. Use associative array to add elements
Associative array means that each element in it has a key value. An associative array is similar to an indexed array, except that it uses strings as keys for array elements. The following is a sample code for adding elements using an associative array:
<?php $arr3 = array("fruit1"=>"apple", "fruit2"=>"banana", "fruit3"=>"orange"); $arr3["fruit4"] = "grape"; $arr3["fruit5"] = "mango"; print_r($arr3); ?>
The output is as follows:
Array ( [fruit1] => apple [fruit2] => banana [fruit3] => orange [fruit4] => grape [fruit5] => mango )
In the above sample code, we have used an associative array to add "grape" and "mango" to The end of array $arr3.
Summary
This article introduces how to add elements to an array in PHP. We can achieve this using array_push() function, indexed or associative arrays. Using these methods, we can add to the array conveniently and quickly, making our program more efficient.
The above is the detailed content of How to add elements to array in php. For more information, please follow other related articles on the PHP Chinese website!