Fox
Fox

Reputation: 17

having trouble with in_array

I have a multidimensional array and i want to check if an array key consists of more than 1 value, so i used count to count all the values of each array key and put it in a separate array, and i got:

Array
(
    [0] => 1
    [1] => 4
    [2] => 6
    [3] => 2
)

Now, my problem is i need to filter it so i can make a condition if the array returns more than two values or just one value, like if:

Array
(
    [0] => 1
    [1] => 1
    [2] => 1
    [3] => 1
)

I have this code so far but it always proceeds to my function display_single_passage(). I believe my problem is within the in_array but I can't seem to figure out how to check if your looking for a number more than 2.

foreach ($passageArray as $sentences) {
            $count = count($sentences);
            $sentenceCount[] = $count; //This is my array of counted values
        }
            if (in_array("/[^2-9]+/", $sentenceCount)) {
                display_multiple_passage(); 
            } else {
                display_single_passage();   
            }

Upvotes: 0

Views: 66

Answers (2)

xdazz
xdazz

Reputation: 160833

The string "/[^2-9]+/" will never in your array.

Example:

if (count(array_filter($passageArray, function($var) {return count($var) > 1;})) > 0) {
    display_multiple_passage(); 
} else {
    display_single_passage();   
}

Upvotes: 1

Viridis
Viridis

Reputation: 242

I am not entirely sure if you'll actually search the regex in the array, or the actual string "/[^2-9]+/". Easy way to solve this is simply loop over the array yourself, and check the values.

$i = 0;
foreach($sentenceCount as $sentenceLength){
    if($sentenceLength > 1){
        display_multiple_passage();
        break;
    }else{
        $i++;
    }
}
if($i == count($sentenceCount)){
    display_single_passage();   
}

This should do it ... even though it would indeed be cleaner if the in_array thing worked :S

Also, can you fix your indentation of your if() block in your second code block please? ^__^

Upvotes: 1

Related Questions