Simply
$os = array("Mac", "NT", "Irix", "Linux");
if (!in_array("BB", $os)) {
echo "BB is not found";
}
Answer from Elyor on Stack Overflowhow to check element is present in array or not in php ?
[SOLVED] Not in array
php while not in_array()
Official/Standard way for checking if array is empty
Videos
Recently a small disagreement occurred at a code review when my new colleagues used [] === $array for checking if array is empty. I requested a change because I always check for empty array with empty($array) and I have never honestly seen [] === $array used before. I even needed to check if it works as expected.
Their argument was that empty has some loose behavior in some cases but I disagreed because we use PhpStan and in every place it is guaranteed that array and nothing else will ever be passed.
I thought about it and the only objective argument that I could brought up is that it's the only way it was done up to this point and it would be weird to start doing it in some other way. I found this 3 years old post from this subreddit by which it looks like the most preferred/expected way is empty($array).
So my question is: Is there some standard or official rule that clearly states the "best" way to do this? For example PSR standard or standard in Symfony ecosystem or something? Is there some undeniable benefits for one way or another?
edit: user t_dtm in refered post points out interesting argument for count($array) === 0:
it won't require massive refactoring if the array gets replaced with some type of Countable (collection, map, list, other iterable)...
edit2: It seems to me that [] === $array is not futureproof because of collections and \Countable and so on... empty has the same issue. That would point me to the \count($array) === 0 way that doesn't have those problems.
Use preg_grep like so:
if (in_array("Notecards", $array) || preg_grep("/Poster\s\d+/", $array)){
echo "Match found";
}else{
echo "Match not found";
}
I took the liberty of assuming that you might have more than Posters 0-9, in which case \d+ matches one or more digits (Poster 10, Poster 800, etc.). If you only require one digit, remove the +.
This is one solution:
if (in_array("Notecards", $array) || substr_in_array("Poster", $array)){
echo "Match found";
}else{
echo "Match not found";
}
substr_in_array($str, $array){
$length = strlen($str);
foreach($array as $value){
if(substr($value, 0, $length) == $str){
return true;
}
}
return false;
}
You can use array_diff() to compute the difference between two arrays:
$array1 = array(1, 2, 3, 4, 5);
$array2 = array(2, 4, 5);
$array3 = array_diff($array1, $array2);
print_r($array3);
Output:
Array
(
[0] => 1
[2] => 3
)
Demo!
$array1 = array(1, 2, 3, 4, 5);
$array2 = array(2, 4, 5);
$result = array_diff($array1, $array2);