How to reindex an array element in PHP
In computer science, an array is a data structure. It contains a collection of elements. Each element has a specific identification. Elements can be identified as an index or key. An array is stored in computer memory in such a way that, it can be computed through its index by different mathematical formulas. Now, what is array reindex? Reindex means, arranging the array elements serial by.
In this tutorial, we are going to learn how to reindex an array element in PHP with examples.
Let’s think, we have an array named myCarArray[] and in this array, we have some car information like name, founded, founder. At first, it is indexed correctly as 0,1,2.
<?php
$myCarArray = [
'0' => [
'name' => 'Ford',
'founded' => '1903',
'founder' => 'Henry Ford'
],
'1' => [
'name' => 'Tesla',
'founded' => '2003',
'founder' => 'Elon Musk'
],
'2' => [
'name' => 'Toyota',
'founded' => '1937',
'founder' => 'Kiichiro Toyoda'
],
];
print_r($newCarArray);
?>
If we see the output of this array in a raw form in the browser-
OUTPUT:
Now, to understand the reindex array, at first we have to unset it by using the unset() function. The unset() function resets any variable. Suppose, we want to remove index 1 which is the Tesla.
unset($myCarArray[1]);
OUTPUT:
If we look into the output, we can see that index 1 is no more but it is not indexed correctly. Index 2 or Toyota came after index 0 or Ford. Now, we need to reindex the array. To reindex the array we are going to use the array_values() function. The array_values() function returns an array containing all the values of an array that is indexed properly.
$newCarArray = array_values($myCarArray);
print_r($newCarArray);
The array_values() takes an array as a parameter, in our case which is $myCarArray and we can simply stored in a variable like $newCarArray.
OUTPUT:
Now, you can see in the output Toyota is returned as index 1.
So, that’s how we can reindex an array in PHP. I hope, this will help you. Thank you.