0

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?

3
  • What is value of $base in this case? Commented Apr 6, 2021 at 22:28
  • if the the url is example.url/web/page/fruit then it would be "fruit". if I echo $base, I get fruit. Commented Apr 6, 2021 at 22:30
  • 2
    so you should use array_key_exists() instead Commented Apr 6, 2021 at 22:31

1 Answer 1

1

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']);
}
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.