If I have a array:
$myarray = array("10"=>"apple", "20"=>"banana", etc..) up to 15 values.

and I use $_GET['category'] to get my value from url for instance "10"

How do I echo $myarray to be "apple"?

Recommended Answers

All 2 Replies

Member Avatar for diafol
if(isset($_GET['category'])){
    $cat = $_GET['category'];
    if(isset($myarray[$cat])){
        echo $myarray[$cat];
    }else{
        echo "Not found in array";
    }
}    

You can also use array_key_exists

if(array_key_exists('category',$_GET)) {
    if(array_key_exists($_GET['category'], $myarray)) {
        echo $myarray[$_GET['category']];
    } else {
         echo 'not found in array';
    }
}

and shorter and not so pretty.....

if(array_key_exists('category',$_GET)) {
    echo array_key_exists($_GET['category'], $myarray) ? $myarray[$_GET['category']] : 'not found in array';
}

and shorter....and uglier.....

echo (array_key_exists('category',$_GET) AND array_key_exists($_GET['category'], $myarray)) ? $myarray[$_GET['category']] : 'not found in array';
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.