In PHP, we often use arrays. However, in some cases, we need to convert the reference array into a normal array, which can bring great convenience to our development. This article will introduce how to convert a reference array into a normal array.
A reference array directly modifies the original array when the elements in the array are manipulated. In layman's terms, two variables point to the same array, and operations on one variable will directly affect the other variable.
Many times we need to convert reference array into ordinary array, because reference array has the characteristics of in-place modification and it is easy to modify The original array is misoperated, and in some cases, we need to perform some sorting, flipping, etc. operations on the array, then we need to convert the reference array into a normal array.
The following is how to convert a reference array into a normal array:
<?php $ref_arr = array(1,2,3); $normal_arr = $ref_arr; print_r($normal_arr); ?>
First create a reference array $ref_arr
, and then use the $normal_arr
variable , copy the value of $ref_arr
to $normal_arr
. In this way, $normal_arr
becomes a normal array and no longer has the feature of in-place modification.
If we make modifications on $normal_arr
, $ref_arr
will not be affected.
<?php $ref_arr = array(1,2,3); $normal_arr = $ref_arr; $normal_arr[0] = 4; print_r($ref_arr); print_r($normal_arr); ?>
The output results are as follows:
Array ( [0] => 1 [1] => 2 [2] => 3 ) Array ( [0] => 4 [1] => 2 [2] => 3 )
You can see that modifying $normal_arr
will not affect $ref_arr
.
It should be noted that after converting the reference array into an ordinary array, the ordinary array no longer has any relationship with the original array, that is to say, Modifications to ordinary arrays will not affect the original array.
In addition, when the original array contains a multi-dimensional array, you need to use recursion to convert all sub-arrays into ordinary arrays to ensure that all the original arrays are converted into ordinary arrays.
Summary
Reference arrays are very useful in some situations, but they can also bring some inconveniences. In order to facilitate the operation of arrays, we can convert reference arrays into ordinary arrays. The conversion method is simple and easy to understand. It should be noted that after conversion, there is no connection between the ordinary array and the original array.
The above is the detailed content of How to convert reference array into ordinary array in php. For more information, please follow other related articles on the PHP Chinese website!