Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you reindex an array in PHP but with indexes starting from 1?

I have the following array, which I would like to reindex so the keys are reversed (ideally starting at 1):

Current array (edit: the array actually looks like this):

Array (

[2] => Object
    (
        [title] => Section
        [linked] => 1
    )

[1] => Object
    (
        [title] => Sub-Section
        [linked] => 1
    )

[0] => Object
    (
        [title] => Sub-Sub-Section
        [linked] => 
    )

)

How it should be:

Array (

[1] => Object
    (
        [title] => Section
        [linked] => 1
    )

[2] => Object
    (
        [title] => Sub-Section
        [linked] => 1
    )

[3] => Object
    (
        [title] => Sub-Sub-Section
        [linked] => 
    )

)
like image 697
meleyal Avatar asked Oct 02 '22 14:10

meleyal


People also ask

How do you make an array index start from 1?

Base Index of Java arrays is always 0. It cannot be changed to 1.

How do I re index an array in PHP?

The re-index of an array can be done by using some inbuilt function together. These functions are: array_combine() Function: The array_combine() function is an inbuilt function in PHP which is used to combine two arrays and create a new array by using one array for keys and another array for values.

Can we change the starting index of an array from 0 to 1 in any way?

Explanation: No. You can not change the C Basic rules of Zero Starting Index of an Array.


2 Answers

Why reindexing? Just add 1 to the index:

foreach ($array as $key => $val) {
    echo $key + 1, '<br>';
}

Edit   After the question has been clarified: You could use the array_values to reset the index starting at 0. Then you could use the algorithm above if you just want printed elements to start at 1.

like image 11
Gumbo Avatar answered Oct 10 '22 18:10

Gumbo


If you want to re-index starting to zero, simply do the following:

$iZero = array_values($arr);

If you need it to start at one, then use the following:

$iOne = array_combine(range(1, count($arr)), array_values($arr));

Here are the manual pages for the functions used:

  • array_values()
  • array_combine()
  • range()
like image 488
Andrew Moore Avatar answered Oct 10 '22 18:10

Andrew Moore