0
Array :  [{"ID":1},{"ID":2}]

$id=1;

I want to check if $id exists in the array.

Thank you!

3
  • check json_decode($string, TRUE); php.net/manual/en/function.json-decode.php Commented Dec 1, 2016 at 10:49
  • json_decode needs string, here i have an array Commented Dec 1, 2016 at 10:50
  • iterate the array using for loop and use the value as a param to json_decode Commented Dec 1, 2016 at 10:51

5 Answers 5

4

You may try Laravel's Collection::contains method, for example:

$collection = collect(json_decode($jsonString, true));

if ($collection->contains(1) {
    // Exists...
}

Also, you may use key/value pair like this:

if ($collection->contains('ID', 1) {
    //...
}

Also, if you want to get that item from the collection then you may try where like this:

$id = $collection->where('ID', 1)->first(); // ['ID' => 1]
Sign up to request clarification or add additional context in comments.

Comments

0

You have a json formatted array and you need to decode it using json_decode first. After that loop the array to check for the id that you want.

So the code should look like this:

$json = '[{"ID":1},{"ID":2}]';
$id = 1;

$data = json_decode($json, true);
foreach($data as $item){
   if($item['id'] == $id) {
      echo 'it exists';
   }
}

1 Comment

json_decode90 expects parameter 1 to be string, array given
0

Iterate the array using for loop and use the value as a param to json_decode.

$id = 1;
$arr = array('{"ID":1}', '{"ID":2}');
foreach($arr as $val) {
  if (in_array($id, json_decode($val, TRUE))) {
    echo "id present";
  }
}

Comments

0

Try this, if value is exist it will give key of array

$jsondata = '[{"ID":1},{"ID":2}]';
$array = json_decode($jsondata,true);

$key = array_search(1, array_column($array, 'ID'));

Comments

0

Just check if the string is in the json array, with little computation.

I think it's the more efficient way. Check the result here.

<?php
$id = 1;
$array = ['{"ID":1}', '{"ID":2}'];
echo in_array(json_encode(["ID" => $id]), $array) ? 'Yes' : 'No';

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.