Tandy
Tandy

Reputation: 1

Php, Why won't in_array on first level of multi-dimensional arrays work?

Say I have a multi-dimensional array like this,

$details = array(
    'fruit' => array(
        'path' => '/tmp/fruit',
        'headers' => array(
            'size',
            'weight',
            'colour')),
    'car' => array(
        'path' => '/tmp/car',
        'headers' => array(
            'model',
            'fuel',
            'colour')),
    'animal' => array(
        'path' => '/tmp/animal',
        'headers' => array(
            'species',
            'sex',
            'locale'));

Why won't this work? Lets say the url is example.url/web/page/fruit

$uriPath = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);

$base = basename($uriPath);

if(in_array($base, $details)) {
    echo($details[$base]['path']);
}

Is there a better way?

Upvotes: 0

Views: 62

Answers (1)

biesior
biesior

Reputation: 55798

in_array() checks if required value exists in array, while you want to check if given key exists in array, use array_key_exists() instead.

if(array_key_exists($base, $details)) {
    echo($details[$base]['path']);
}

Upvotes: 1

Related Questions