Ask Your Question
3

What is the method to reindex an array in PHP in such a way that the indexes start from 1?

asked 2023-05-28 10:37:26 +0000

ladyg gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2023-05-28 10:56:01 +0000

huitzilopochtli gravatar image

To reindex an array in PHP in such a way that the indexes start from 1, you can simply use the array_values() function. This function returns a new array containing all the values of the original array, with numeric keys starting from 0 and increments by 1. By subtracting 1 from all the keys of the resulting array, we can reindex the array with keys starting from 1.

Here's an example code:

<?php
$myArray = array("apple", "banana", "cherry");
$reindexedArray = array_values($myArray);
$finalArray = array_combine(range(1, count($reindexedArray)), $reindexedArray);
print_r($finalArray);
?>

Output:

Array
(
    [1] => apple
    [2] => banana
    [3] => cherry
)

In this example, we first get the reindexed array using the array_values() function. Then, we use the array_combine() function to combine the numeric array keys starting from 1 with the values of the reindexed array, creating a new array with keys starting from 1.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-05-28 10:37:26 +0000

Seen: 11 times

Last updated: May 28 '23