Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change indexing of array in php

Tags:

arrays

php

I want to change the indexing of array for example. I have an array

$a = array("a","e","i","o","u");
echo $a[0]; //output a

It means this array has index (0,1,2,3,4)

Now I want to start my array from index 100 instead 0

Means array with index (100,200,300,400,500)

like image 678
Bhuvnesh Gupta Avatar asked Feb 19 '23 09:02

Bhuvnesh Gupta


1 Answers

If you want to declare an array that way you should do:

$array = array(100 => 'a', 200 => 'b', 300 => 'c', 400 => 'd', 500 => 'e');

Note that if you add a new element to the $array in the shorter way ($array[] = 'f') the key assigned will be 501.

If you want to convert regular array indexes to hundreds-based ones you can do this:

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

But perhaps you don't really need to convert no array and instead access your current one this way:

$i = $hundredBasedIndex / 100 - 1;
echo $array[$i];
// or directly
echo $array[($hundredBasedIndex / 100 - 1)];
like image 157
Carlos Avatar answered Feb 26 '23 23:02

Carlos