0

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
1

1 Answer 1

3

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
Sign up to request clarification or add additional context in comments.

3 Comments

@Md.SahadatHossain (didn't copied the entire code now it works)
Using end, followed by prev might be better, if you know that the key from which the loop must start is known to exist. But that's micro-optimization anyways
How if i only want to list specific array keys, exp. 126,155,45 ?, thanks before

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.