CMH
CMH

Reputation: 738

Find index of an element in an array in PHP

I'm trying to find a string in an array and then return the index and check that index in another array to see if it matches (I'm looking for open times and matching close times in the arrays respectively).

The string might appear more than once in $openList, and it shouldn't stop checking until it's found a pair of matching times in both $openList and $closeList. array_search only finds the first occurrence so I'm having trouble creating a loop that works and is efficient (I'll be running this multiple times with different search values).

So far, I have something like:

$openList = array("10:00", "9:00", "10:15", "9:00", "2:30");
$closeList = array("2:15", "5:30", "10:30", "10:00", "3:00");

$found_key = false;
while (($key = array_search("9:00", $openList)) !== NULL) {
  if ($closeList[$key] == "10:00") {
    $found_key = true;
    echo "found it at position ".$key;
    break;
  }
}
if (!$found_key) echo "time doesn't exist";

How can I fix it in an efficient way?

Upvotes: 0

Views: 170

Answers (3)

CMH
CMH

Reputation: 738

Thanks for the hint to look at array_keys @David Nguyen. This seems to work:

$openList = array("10:00", "9:00", "10:15", "9:00", "2:30");
$closeList = array("2:15", "5:30", "10:30", "10:00", "3:00");

$found_key = false;
foreach (array_keys($openList, "9:00") AS $key) {
  if ($closeList[$key] == "10:00") {
    $found_key = true;
    echo "found it at position ".$key;
    break;
  }
}
if (!$found_key) echo "time doesn't exist";

Upvotes: 0

Don Rhummy
Don Rhummy

Reputation: 25820

Your current loop will run forever if there is no "9:00" in the list. Instead, use a foreach loop to look through the $openList array:

foreach ( $openList as $startTimeKey => $startTimeValue )
{
    //Found our start time
    if ( $startTimeKey === "9:00" && isset( $closeList[ $startTimeValue ] ) && $closeList[ $startTimeValue ] === "10:00" )
    {
        $found_key = true;
        break;
    }
}

Upvotes: 0

David Nguyen
David Nguyen

Reputation: 8528

Pretty sure array_keys is exactly what you are looking for:

http://www.php.net/manual/en/function.array-keys.php

Upvotes: 1

Related Questions