Home >Backend Development >PHP Problem >How to add data to a new array in php
PHP is a widely used server-side scripting language used for web development and building dynamic websites. In PHP programming, we often need to add data to a new array to facilitate various operations. This article will introduce how to add data to a new array in PHP.
Method 1: Use the array_push() function
The array_push() function is used to add one or more elements to the end of the array. This function returns the new length of the updated array.
Syntax:
array_push(array, value1, value2, ...)
Among them, array represents the array to which elements need to be added; value1, value2, ... represents the elements that need to be added to the array.
Example:
<?php $students = array('Tom', 'John', 'Peter'); array_push($students, 'Lucy', 'James'); print_r($students); ?>
Output result:
Array ( [0] => Tom [1] => John [2] => Peter [3] => Lucy [4] => James )
Method 2: Use the " " operator
In PHP, you can use the " " operator to Merge two arrays into a new array. If the same key name exists in two arrays, the elements in the second array will overwrite the elements in the first array.
Syntax:
$array = $array1 + $array2;
Among them, $array1 and $array2 are the two arrays to be merged.
Example:
<?php $students1 = array('Tom', 'John', 'Peter'); $students2 = array('Lucy', 'James'); $students = $students1 + $students2; print_r($students); ?>
Output result:
Array ( [0] => Tom [1] => John [2] => Peter [3] => Lucy [4] => James )
Method 3: Direct assignment
In PHP, you can directly assign an element to a new array A specified key name. If the key name already exists, the element corresponding to the key name is overwritten.
Example:
<?php $students = array(); $students['English'] = 'Tom'; $students['Math'] = 'John'; $students['Science'] = 'Peter'; print_r($students); ?>
Output result:
Array ( [English] => Tom [Math] => John [Science] => Peter )
The above are the three methods of adding data to a new array in PHP. Choosing the appropriate method according to actual needs can operate the array more efficiently.
The above is the detailed content of How to add data to a new array in php. For more information, please follow other related articles on the PHP Chinese website!