2

I have an array that looks like this var_dump($result):

$result = array(
    array("Start" => array("xxxx")),
    array("Driving route" => array("xxxx")),
    array("Lunch-Rest Break" => array("xxxx")),
    array("Break" => array("xxxx")),
    array("Waiting" => array("xxxx")),
    array("End" => array("xxxx"))s
);

How can I get the index of a given key? For instance I wanted to get the index of the key "Break" I did as folowing :

$key = array_search('Break', $result);

$key is empty I get no index.

Thanks.

1
  • array_search() is not recursive, but there's plenty of examples in the PHP manual doc page comments showing ways of implementing a recursive array search Commented Feb 2, 2014 at 12:44

1 Answer 1

2

Here is a function :

$result = array(
    array("Start" => array("xxxx")),
    array("Driving route" => array("xxxx")),
    array("Lunch-Rest Break" => array("xxxx")),
    array("Break" => array("xxxx")),
    array("Waiting" => array("xxxx")),
    array("End" => array("xxxx"))
);

function searchKeyIndex($array, $key) {
    for($i = 0; $i < count($array); $i++) {
        if(isset($array[$i][$key])) {
            return $i;
        }
    }
}

echo searchKeyIndex($result, "Break");

Output : 3

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

Comments

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.