php - How to select several array elements and check if they are equal to variable ← (PHP)

I'm trying to learn PHP on my own just by watching videos and reading blogs. I won't become a pro, I'm just a hobbyist. So I'm trying to code something but I got to a dead end. So I have a string, let's say the string has some numbers f.e. 100, 2000, 3000. Using the explode method I convert the string to an array. Now I have a variable f.e. $var= 50;

I want to see if $var is equal to the first or the third element of the array;

<?php
    $str = " 100, 2000, 3000";
    $fevArr = explode(",", $str);
    $var = 50;
    if ($var == $fevArr['0'] or $var == $fevArr['2'] ) {
        echo "It is";
    } else {
        echo "It is not";
    }
?>

However I might have a lot of numbers in the string and I may want to check if $var is eaqual to many of them (say to the 1th, 10th, 20th, 101th, 300th ect). So I wonder if there is a way to make soemthing like this:

if ($var == $fevArr['0', '9', '19',]) { ....

In other words if there is a way to select several array elements at once.

Answer



Solution:

Yes you can use array_keys function. It will return all the indices that match the value you want to look for. Then you can use array_intersect function to check whether those indices match your indices you want to look for.

$var = 50;
$indices = [0, 2];
$keys = array_keys($fevArr, $var);
$matches = array_intersect($indices, $keys);

if(count($matches) > 0) {
   ...
}

Answer



Solution:

You can use in_array($var, $fevArray) (see documentation) in your if statement.

Answer



Solution:

You can use either array_search (link) which returns the key of the first match and false if no match found OR you can use in_array (link) method which will just check the existance.

Answer



Solution:

in_array() is not consistent just like this

you can use the following code, I got it here

function contains($str, array $arr)
{
    foreach($arr as $a) {
        if (stripos($str,$a) !== false) return true;
    }
    return false;
}

and you can apply it as:

if (contains($var, $fevArr) {
 echo "It is";
}
else {
 echo "It is not";
}

Answer



Solution:

<?php
    function contains_at_keys($haystack, $needle, $keys){
        //get all keys matching needle
        $matching_keys = array_keys($haystack, $needle);
        
        //return if these keys contain one or more of the keys to search
        return(sizeof(array_intersect($matching_keys, $keys)) > 0);
    }
    
    
    $str = "100, 2000, 3000, 50, 300, 50, 200";
    $fevArr = explode(",", $str);
    $var = 50;
    
    $keys = [3, 5];
    
    
    if(contains_at_keys($fevArr, $var, $keys)){
        echo("It is");
    } else {
        echo("It is not");
    }
?>

Source