-1

Having the following string:

"[{"name":null,"value":"","target":null,"alias":"","required":1,"showNull":0}]"

How can I get the 1 from the required part? I need just the 1.

Thanks in advance.

Avión
  • 7,963
  • 11
  • 64
  • 105
  • Why not parse the json? or isn't it always valid? – Jerodev Feb 17 '17 at 08:57
  • First of all your string is not valid. If you have valid string you can try json_decode(), after that you can get with required key. – Vahe Galstyan Feb 17 '17 at 08:59
  • @VaheGalstyan The string is valid JSON... https://eval.in/739285 – BenM Feb 17 '17 at 09:01
  • @BenM please check string in your example and string in question, your string start with ' , but in question it start with " . – Vahe Galstyan Feb 17 '17 at 09:04
  • @VaheGalstyan The actual content of the string itself is valid JSON. Indeed, the example the OP has added is not a valid string in PHP, but I assumed it was a demonstration. – BenM Feb 17 '17 at 09:09
  • @BenM question about php, it's a reason why I said that ). Without that I Accept your mind. – Vahe Galstyan Feb 17 '17 at 09:12

3 Answers3

3

Assuming the string will always be JSON, use json_decode():

$array = json_decode('[{"name":null,"value":"","target":null,"alias":"","required":1,"showNull":0}]');

Now you can access the required option as follows:

$array[0]->required;
BenM
  • 52,573
  • 26
  • 113
  • 168
0

You can use json_decode:

<?php
$string = '[{"name":null,"value":"","target":null,"alias":"","required":1,"showNull":0}]';
$string_array = json_decode($string, true);
echo $string_array[0]['required'];
?>
Akam
  • 1,089
  • 16
  • 24
0

In single line, using the functions json_decode and current:

$str = '[{"name":null,"value":"","target":null,"alias":"","required":1,"showNull":0}]';
$required = current(json_decode($str))->required;
user2342558
  • 5,567
  • 5
  • 33
  • 54