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

if(isset($_GET['category'])){
    $cat = $_GET['category'];
    if(isset($myarray[$cat])){
        echo $myarray[$cat];
    }else{
        echo "Not found in array";
    }
}    
Jump to Post

All 2 Replies

Member Avatar
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 1.20 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.