OussamaLord
OussamaLord

Reputation: 1095

get index of complex array in PHP

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.

Upvotes: 2

Views: 107

Answers (1)

S.Thiongane
S.Thiongane

Reputation: 6905

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

Upvotes: 2

Related Questions