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

Asked

Viewed 1,281 times

1

How can I check for the "2017-11-15" string 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 that way and I couldn’t:

$string = "2017-11-15";
if(in_array($string, (array) $proposal_dates)){
        echo 'existe no array.';
    } else{
        echo 'nao existe no array';
    }
  • Can’t store a string in place of the object? so it’s easier to compare.

  • you say the return of the array?

  • Yeah, you’re using the class DateTime()?

  • This array comes from the database, I make a select and returns to me all dates referring to that ID. I am not using this class.

2 answers

2

If it didn’t work out the way you did (I believe it’s pq vc has an object inside the array), you can try going through the entire array and go through it one by one like this :

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

1


Use array_map() to extract the value of the object return an array with only the value, then you can directly compare the 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';
}
  • Thanks rray, it worked out! I was thinking of converting to json and check if there is this string inside the json

Browser other questions tagged

You are not signed in. Login or sign up in order to post.