Changing array indexing in php

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

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

This means that this array has an index (0,1,2,3,4)

Now I want to run my array from index 100 instead of 0

Means with an index (100 200 300 400 500)

+4
source share
7 answers

If you want to declare an array this way, which you should do:

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

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

If you want to convert regular array indices to hundreds-on-one, you can do this:

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

But perhaps you do not need to convert the array and refer to your current one instead:

 $i = $hundredBasedIndex / 100 - 1; echo $array[$i]; // or directly echo $array[($hundredBasedIndex / 100 - 1)]; 
+5
source

Another solution:

 $a = array_combine(array(100, 200, 300, 400, 500), $a); 
+4
source

You can simply determine the starting index and iterate over the array by swapping indices. Something like that -

 $oldArray = array("a","e","i","o","u"); $newArray = array(); $startIndex = 100; foreach($oldArray AS $key => $value){ $newArray[$startIndex] = $value; startIndex += 100; } 
+1
source

just create an associative array with the keys you need. eg:

 $myArray = array(100=>"a",200=>"e",300=>"i",400=>"o",500=>"u"); 

then you call values ​​like:

 echo $myArray[100] ; 

Note: do not put '100'=>"a" instead of 100=>"a"

0
source

$ key = array (100, 200, 300, 400, 500);

$ b = array_combine ($ key, $ a);

0
source

Just create an array this way.

 $myarray = array( 100 => 'a', 200 => 'b', ); 

If you already have an array with this order and you want to multiply the keys by 100, you can do this in a loop (there are other ways, but ...):

 $a = array('a', 'b', 'c', 'd', 'e'); $newarray = array(); foreach($a as $key => $value) $newarray[100*($key+1)] = $value; 
-1
source

Just change your array Like this:

 $a = array(100 => "a", 200 => "e", 300 => "i", 400 => "o", 500 => "u"); 
-1
source

Source: https://habr.com/ru/post/1447697/


All Articles