php check if json key exists – How to check if key is present in json in PHP?

5/5 - (1 vote)

I need a value of the key to be present in JSON so we can use this value in our system.if..else also can handle to check key exists or not in objects.

Free Live Chat for Any Issue

php check if json key exists – check if key is present in json in PHP

if( isset( $memInfo['mem_id'] ) ){
   // do something
}

Also you can read : Json Object Check If Value Exists Example

here you can know whether key exists in Json string.

if(array_key_exists('mem_id', $memInfo)) {
    //key exists, do stuff
}

php check if json key exists

if don’t exist key json php

<?php
$playerData = array('game' => 1, 'cricket' => 4);
if (array_key_exists('game', $playerData)) {
    echo "The 'game' element is in the array";
}
?>

check if value exists in json array php

//Find if value exists in a JSONArray in php

$array = json_decode($json, true);
if (in_array('e', $array['output'])) {
    ...
}

check if value exists in json object php

Read Also:  php get percentage of two numbers - 3 Ways to calculate a percentage change (increase and decrease) from 2 values in PHP

$json = '{
"response": {
    "play_count": 106,
    "plays": [
        {
            "shop_id": 25,
            "playtime_news": 67
        },
        {
            "shop_id": 8965,
            "playtime_news": 0
        },
        {
            "shop_id": 565656,
            "playtime_news": 0
        },
        {
            "shop_id": 989666,
            "playtime_news": 0
        } // <------ note the lack of `,`
        ]
    }
}';

$arr = json_decode($json, true);

foreach($arr['response']['plays'] as $play) {
    if($play['shop_id'] === 8965) { // I would strictly check (type) incase of 0
        echo "exists"; // or do something else
        break; // break out if you dont care about the rest
    }
}

php json_decode get key name

//get key value from json object in php

// json object.
    $allInfo = '{"profile":"John", "account":"Doe"}';

    // Option 1: through the use of an array.
    $jsonArray = json_decode($allInfo,true);

    $key = "profile";

    $profile = $jsonArray[$key];


    // Option 2: through the use of an object.
    $jsonObj = json_decode($allInfo);

    $profile = $jsonObj->$key;

check if key value pair exists in array php

//How can I check if a key/value pair exists in php?

<?php

$parrents = array(
    array("collage" => "Foo collage",
    "saved" => true
  ),
  array(
    "collage" => "Bar collage",
    "saved" => false
  ));

$shopData = "";
$status = false;
foreach ($parrents as $parrent) {
    if (isset($parrent['saved']) && $parrent['saved']) {
       echo $parrent['collage'];
       $status = true;
       break;
    } else {
       $shopData .= $parrent['collage'] . "<br />";
    }
}

if (!$status) {
    echo $shopData;
}

?>

Download

Ref : array_key_exists ‚ÄĒ Checks if the given key or index exists in the array