To re-index an array in PHP, the code is as follows −
Example
<?php
$arr = array( 0=>"150", 1=>"100", 2=>"120", 3=>"110", 4=>"115" );
echo "Array...\n";
foreach( $arr as $key => $value) {
echo " Key = " . $key . ", Value = " . $value . "\n";
}
$arr = array_combine(range(2,
count($arr) + (1)),
array_values($arr));
echo "\nArray after re-indexing\n";
foreach( $arr as $key => $value) {
echo " Key = " . $key . ", Value = " . $value . "\n";
}
?>Output
This will produce the following output−
Array... Key = 0, Value = 150 Key = 1, Value = 100 Key = 2, Value = 120 Key = 3, Value = 110 Key = 4, Value = 115 Array after re-indexing Key = 2, Value = 150 Key = 3, Value = 100 Key = 4, Value = 120 Key = 5, Value = 110 Key = 6, Value = 115
Example
Let us now see another example −
<?php
$arr = array( "a"=>"150", "b"=>"100", "c"=>"120", "d" =>"110", "e"=>"115" );
echo "Array...\n";
foreach( $arr as $key => $value) {
echo " Key = " . $key . ", Value = " . $value . "\n";
}
$arr = array_combine(range("b",
chr(count($arr) + (ord("b")-1))),
array_values($arr));
echo "\nArray after re-indexing\n";
foreach( $arr as $key => $value) {
echo " Key = " . $key . ", Value = " . $value . "\n";
}
?>Output
This will produce the following output−
Array... Key = a, Value = 150 Key = b, Value = 100 Key = c, Value = 120 Key = d, Value = 110 Key = e, Value = 115 Array after re-indexing Key = b, Value = 150 Key = c, Value = 100 Key = d, Value = 120 Key = e, Value = 110 Key = f, Value = 115