Jennifer Anthony
Jennifer Anthony

Reputation: 2277

Compare against each value in a Json encoded array

How can compare each a from content json_encode that inserted in database with a string as shorthand code without use loop? (this values was checkbox that inserted in database with json_encode)

Example

$json_encode = ["how", "are", "hello", "what"];

echo ($json_encode == 'hello') ? 'It is true' :'';

Upvotes: 0

Views: 1071

Answers (2)

SW4
SW4

Reputation: 71190

The code is a little bit of a 'round a bout' way of doing things but this should do the trick:

$json_encode = '["how", "are", "hello", "what"]';    
echo ( in_array('hello', json_decode($json_encode)) ? 'It is true' :'' );

Your initial $json_encode isnt setup correctly as a proper JSON string, and required decoding to use the array checking functionality later on.

A better approach maybe:

$json_string = json_encode(array("how", "are", "hello", "what"));
echo ( in_array('hello', json_decode($json_string )) ? 'It is true' :'' );

Upvotes: 1

Tudor Constantin
Tudor Constantin

Reputation: 26861

try with in_array() function:

$json_encode = ["how", "are", "hello", "what"];

echo ( in_array('hello', $json_encode) ? 'It is true' :'' );

Upvotes: 0

Related Questions