In PHP programming, we often encounter situations where we need to remove the same subscripts in an array, but we don’t know how to achieve it. In this article, we will share some practical methods to remove identical subscripts from arrays in PHP.
Sample code:
<?php $arr = array("a"=>1, "b"=>2, "c"=>2, "d"=>1); $new_arr = array_unique(array_flip($arr)); print_r($new_arr); ?>
Execution result:
Array ( [1] => a [2] => b )
Sample code:
<?php $arr = array("a"=>1, "b"=>2, "c"=>2, "d"=>1); $new_arr = array_flip(array_keys(array_flip($arr))); print_r($new_arr); ?>
Execution result:
Array ( [a] => 1 [b] => 2 )
Sample code:
<?php $arr = array("a"=>1, "b"=>2, "c"=>2, "d"=>1); $new_arr = array(); foreach($arr as $key=>$value){ if(!in_array($key,$new_arr)){ $new_arr[$key] = $value; } } print_r($new_arr); ?>
Execution result:
Array ( [a] => 1 [b] => 2 )
To sum up, this article introduces three methods to remove the same subscripts in PHP arrays. The scenarios used and the effects to be achieved are different, so you can choose the corresponding method according to the actual situation.
The above is the detailed content of Remove the same subscripts from php arrays (three methods). For more information, please follow other related articles on the PHP Chinese website!