Monday, 13 August 2018

How to Reindex an Array in PHP?

Problem:

You have an indexed array. Some values from this array are removed. See the following array. Now, you want to re-index the array, meaning serialize the keys staring keys from 0 and incrementing by 1. 
1
2
3
4
5
6
7
8
$cars = array(
    2 => “Alco”,
    3 => “Alesia”,
    4 => “BAZ”,
    7 => “BMW”,
    10 => “Chery”,
    11 => “Eagle”
)

Solution:

array_values() function will help you re-index the array and sort the keys from 0 serially. See the following example-
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<pre>
<?php
$cars = array(
    2 => "Alco",
    3 => "Alesia",
    4 => "BAZ",
    7 => "BMW",
    10 => "Chery",
    11 => "Eagle"
);
 
$cars = array_values($cars);
print_r($cars);
?>
</pre>

Output:

0 comments:

Post a Comment