AtomicSteed AtomicSteed - 2 years ago 69
PHP Question

Go to a section in the array, then echo what is next

Here I have an array of just words. I'm trying to go to a section of the array and then echo the item that comes right after it. (Look for Dog then echo Cat)

It seems it's unable to compare items with the code I have here, and thus creates an endless loop. It works just fine if I replace $Current = 'Dog' to $Current = 2 as expected.

Basically is there any way to compare something to an array item without using a number?

$List = array('Lizard', 'Bull', 'Dog', 'Cat', 'Soda', 'Tomato', 'Hand');
$Current = 'Dog';

while (key($List) !== $Current) next($List);
echo next($List);

Answer Source

It works because key() returns the key of the current element ($List).

What you want to do is harness array_search() to find the key (2 in this case) for $Current and compare it:

while (key($List) !== array_search($Current, $List)) next($List);
    echo next($List);




And if that doesn't float your boat, simply change key() to current() to compare the string value instead of the numeric key value.

Don't compare the index of the array. As stated above, compare the current value:

while (current($List) !== array_search($Current, $List)) next($List);
    echo next($List);


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download