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] =>
)
)
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()
Here is the best way:
# Array
$array = array('tomato', '', 'apple', 'melon', 'cherry', '', '', 'banana');
that returns
Array
(
[0] => tomato
[1] =>
[2] => apple
[3] => melon
[4] => cherry
[5] =>
[6] =>
[7] => banana
)
by doing this
$array = array_values(array_filter($array));
you get this
Array
(
[0] => tomato
[1] => apple
[2] => melon
[3] => cherry
[4] => banana
)
Explanation
array_values()
: Returns the values of the input array and indexes numerically.
array_filter()
: Filters the elements of an array with a user-defined function (UDF If none is provided, all entries in the input table valued FALSE will be deleted.)
I just found out you can also do a
array_splice($ar, 0, 0);
That does the re-indexing inplace, so you don't end up with a copy of the original array.
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.