I want to be able to retrieve the value of an array by using the numeric key. The catch is that if the key is beyond the array length, I need it to loop through the array again.
$my_array = array('zero','one','two','three','four','five','six','seven');
function loopArrayValues($array,$key){
//this is what is needed to return
return
}
echo "Key 2 is ".loopArrayValues($my_array,2)."<br />";
echo "Key 11 is ".loopArrayValues($my_array,11)."<br />";
echo "Key 150 is ".loopArrayValues($my_array,11)."<br />";
Expected output:
Key 2 is two
Key 11 is three
Key 150 is three
My research references:
- continuously loop through PHP array (or object keys)
- http://php.net/manual/en/class.infiniteiterator.php
My formed function:
function loopArrayValues($array,$key){
$infinate = new InfiniteIterator(new ArrayIterator($array));
foreach( new LimitIterator($infinate,1,$key) as $value){
$return=$value;
}
return $return;
}
The function works, but I have a question: is this a good way to get the intended results?
` when instead I would want it to return `six` I am trying to use this inside a FPDF function to display a color for a text with a variable color scales, sometimes there might be one color and sometimes there might be 3 colors. First line gets color 1, second line gets color two, etc. and without breaking. – amaster May 17 '13 at 16:47