0

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?

2
  • 4
    you should look at array_key_exists Commented Oct 1, 2013 at 16:54
  • array_key_exists searches the keys, not the content of the array itself. I'm looking for something that searches the array and returns the position it is at. array_keys as @David Nguyen suggests is the better function. Commented Oct 1, 2013 at 17:39

3 Answers 3

1

Pretty sure array_keys is exactly what you are looking for:

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

Sign up to request clarification or add additional context in comments.

Comments

0

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;
    }
}

Comments

0

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";

1 Comment

If my comment did help you solve the issue feel free to mark my answer as the solution to close the question :)

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.