Reputation: 3236
Let I have an array like this
Array
(
[126] => pitch
[134] => pithc2
[155] => pithc3
[87] => pithc4
[45] => pithc5
[192] => pithc6
)
Now is there any way to apply loop in this array from specific key?
Example: I want to output after 155
then output look like
1. pitch4,
2. pithc5
3. pithc6
if I want get output after 45
then output look like
1. pithc6
Upvotes: 0
Views: 588
Reputation: 59681
This should work for you:
Here I use reset()
, next()
, current()
, key()
, end()
to loop through the array as you want it
<?php
$arr = array(126 => "pitch", 134 => "pithc2", 155 => "pithc3", 87 => "pithc4", 45 => "pithc5", 192 => "pithc6");
$from = 134;
//Get last element + rest the array
$end = end($arr);
reset($arr);
//set array pointer to '$from'
while(key($arr) != $from) next($arr);
while(current($arr) != $end) {
next($arr);
//prints the current array element and goes to the next one
echo current($arr) . "<br />";
}
?>
Output:
pithc3
pithc4
pithc5
pithc6
And if you want to limit how many elements should be printed you can use this:
<?php
$arr = array(126 => "pitch", 134 => "pithc2", 155 => "pithc3", 87 => "pithc4", 45 => "pithc5", 192 => "pithc6");
$from = 134;
$howmany = 6;
//Get last element + rest the array
$end = end($arr);
reset($arr);
//set array pointer to '$from'
while(key($arr) != $from) next($arr);
//go through '$howmany' times
for($i = 0; $i < $howmany; $i++) {
//prints the current array element and goes to the next one
echo current($arr) . "<br />";
//rest the array to the beginning, while it reached the end
if(current($arr) == $end)
reset($arr);
else
next($arr);
}
?>
Output:
pithc2
pithc3
pithc4
pithc5
pitch6
pithc
Upvotes: 3