How to check if there is a string in this array?

1

How can I check if there is a string "2017-11-15" in this array?

array(4) {
  [0]=>
  object(stdClass)#43 (1) {
    ["date"]=>
    string(10) "2017-11-13"
  }
  [1]=>
  object(stdClass)#44 (1) {
    ["date"]=>
    string(10) "2017-11-14"
  }
  [2]=>
  object(stdClass)#45 (1) {
    ["date"]=>
    string(10) "2017-11-15"
  }
  [3]=>
  object(stdClass)#46 (1) {
    ["date"]=>
    string(10) "2017-11-16"
  }
}

I tried this and could not:

$string = "2017-11-15";
if(in_array($string, (array) $proposal_dates)){
        echo 'existe no array.';
    } else{
        echo 'nao existe no array';
    }
    
asked by anonymous 14.11.2017 / 18:40

2 answers

1

Use array_map() to extract the value of the object return an array with only the value, then it can compare directly in in_array()

$plainArray = array_map(function($item){ return $item->date;} , $proposal_dates);

if(in_array($string, $plainArray)){
   echo 'existe no array.';
} else{
   echo 'nao existe no array';
}
    
14.11.2017 / 18:52
2

If it did not work the way you did (I think it's because you have an object inside the array), you can try to go through the whole array and check one by one like this:

    foreach ($array as $value) {
        if($value->date == $string)
             echo 'existe no array.';
        } else{
              echo 'nao existe no array';
        }
    } 
    
14.11.2017 / 18:54