How to re-index an array in PHP?


To re-index an array in PHP, the code is as follows −

Example

 Live Demo

<?php
   $arr = array( 0=>"150", 1=>"100", 2=>"120", 3=>"110", 4=>"115" );
   echo "Array...
"; foreach( $arr as $key => $value) {     echo " Key = " . $key . ", Value = " . $value . "
"; } $arr = array_combine(range(2,       count($arr) + (1)),       array_values($arr)); echo "
Array after re-indexing
"; foreach( $arr as $key => $value) {     echo " Key = " . $key . ", Value = " . $value . "
"; } ?>

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 −

 Live Demo

<?php
   $arr = array( "a"=>"150", "b"=>"100", "c"=>"120", "d" =>"110", "e"=>"115" );
   echo "Array...
"; foreach( $arr as $key => $value) {     echo " Key = " . $key . ", Value = " . $value . "
"; } $arr = array_combine(range("b",       chr(count($arr) + (ord("b")-1))),       array_values($arr)); echo "
Array after re-indexing
"; foreach( $arr as $key => $value) {     echo " Key = " . $key . ", Value = " . $value . "
"; } ?>

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

Updated on: 26-Dec-2019

510 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements