1

I found a similar question but it doesn't full fill what I need How to reset keys after unsetting values in an array?

my array is like

$fruits = array(
 [0] => 'apple'
 [1] => 'banana'
 [3] => 'orange'
 [4] => 'melon'
);

With array_values I can reset it starting from 0

array_values($fruits);

// array fixed 
array(4) {
 [0] => 'apple'
 [1] => 'banana'
 [2] => 'orange'
 [3] => 'melon'
}

But I need to reset starting from 1 instead 0, is it possible?

// array fixed
array(4) {
 [1] => 'apple'
 [2] => 'banana'
 [3] => 'orange'
 [4] => 'melon'
}
al404IT
  • 1,380
  • 3
  • 21
  • 54

2 Answers2

2

Please try following code.

function reindex ($arr, $start_index)
{
    $arr = array_combine(range($start_index,  count($arr) + ($start_index - 1)), array_values($arr)); 
    return $arr;
}

Following is my test result.

$arr = array ( 
    0 => 'apple', 
    1 => 'banana', 
    3 => 'orange',  
    4 => 'melon' 
); 

$arr = reindex ($arr, 1);

foreach( $arr as $key => $value) {  
    echo "Index: ".$key." Value: ".$value."\n";  
} 

And following is the output.

Index: 1 Value: apple
Index: 2 Value: banana
Index: 3 Value: orange
Index: 4 Value: melon

You can test this code on following online tester.

http://sandbox.onlinephpfunctions.com/

WebDev
  • 587
  • 1
  • 6
  • 23
1

You can do it by adding 1 to key:

foreach ($array as $key => $value) {
     $array[$key+1] = $array[$key];
     unset($array[$key];
}

But its working just when your array starts with 0 key.

That you can do with: array_values($array);

Marty1452
  • 430
  • 5
  • 19
  • Your answer give me an idea so i whent like: foreach ($array as $key => $value) { echo $key+1 ." = ". $array[$key]; unset($array[$key]; } – Samuel Ramzan Aug 24 '22 at 18:44