2

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'
}
3
  • 2
    array always start with 0 .. make a foreach loop with an iteration and assign a new array yourself starting with 1 Commented Jun 10, 2020 at 16:16
  • 2
    array_combine(range(1,count($fruits)),$fruits); Commented Jun 10, 2020 at 16:16
  • 2
    Why would you want to do this? As pointed out above, normal arrays start at 0. Commented Jun 10, 2020 at 16:18

2 Answers 2

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/

Sign up to request clarification or add additional context in comments.

Comments

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);

1 Comment

Your answer give me an idea so i whent like: foreach ($array as $key => $value) { echo $key+1 ." = ". $array[$key]; unset($array[$key]; }

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.