0

I have this JSON string.

[
   {
     "name": "user_title",
     "value": "Bapak."
   },
   {
     "name": "user_firstname",
     "value": "Test"
   },
   {
     "name": "user_lastname",
     "value": "XXX"
   }
]

This string generated dynamically. It may has more or less. I use JSON Decode to process it in PHP.

$json_form      = json_decode($json_string,true);

$user_title     = $json_form[0]['value'];
$user_firstname = $json_form[1]['value'];
$user_lastname  = $json_form[2]['value'];

How do I check the variable user_title even exist in the string?

If it exist I should get the value but if not that means $user_title = NULL.

Shota
  • 515
  • 3
  • 18
  • Does this answer your question? [how to know whether key exists in Json string](https://stackoverflow.com/questions/10176293/how-to-know-whether-key-exists-in-json-string) – Martheen Jan 27 '21 at 08:15
  • Also, just use their key, *not* their position, such as $json_form["user_title"] instead of $json_form[0], your code will break if the item positions are different – Martheen Jan 27 '21 at 08:17

1 Answers1

1

You might want to consider mapping your JSON into a key/value array using array_column; then it is easy to check for the existence of a value. For example:

$json_form = json_decode($json_string, true);
$values = array_column($json_form, 'value', 'name');

$user_title     = $values['user_title'];
$user_firstname = $values['user_firstname'];
$user_lastname  = $values['user_lastname'];

echo "title: $user_title\nfirst name: $user_firstname\nlast name: $user_lastname\n";

Output for your sample data is:

title: Bapak.
first name: Test
last name: XXX

It's also easy to add default values when a key is missing, for example:

$user_title     = $values['user_title'] ?? '';
Nick
  • 138,499
  • 22
  • 57
  • 95