Question

I'm having trouble with output in for each function in PHP (actually don't know how to set the code to do what I need). I'd like to output some text if every item in foreach is equal to some value. If I put

foreach($items as $item) {
    if($item == 0){ echo "true"; }
}

I will get true for every item and I need to output true only if all items are equal to some value.

Thanks!

Was it helpful?

Solution 2

This peice of code work for most type of variables. See how it works in inline comment.

 $count=0; // variable to count the matched words
 foreach ($items as $item)
   {
     if($item == $somevalue)
       {
         $count++; // if any item match, count is plus by 1
       }
   }
 if($count == count($items))
   {
     echo "true"; // if numbers of matched words are equal to the number of items
   }
 else
  {
    echo "false";
  }

Hope it works , And sorry for any mistake

OTHER TIPS

This is most likely due to PHP type juggling your values. Your values are probably not numeric so when you do a loose comparison (==) PHP converts them to integers. Strings that do not start with digits will become zero and your statement will be true.

To fix this use the === comparison operator. This will compare value and type. So unless a value is the integer zero it will be false.

if($item === 0){ echo "true"; }

If you are trying to see if all items are equal to some value this code will do this for you:

$equals = 0;
$filtered = array_filter($items, function ($var) use ($equals) {
    return $var === $equals;
});
if (count(count($items) === count($filtered)) {
    echo "true";
}
$ok = true;
foreach ($items as $item) 
{
    if ($item != 0)
    { 
        $ok = false;
    }
}
if ( $ok == true)
{
    echo 'true';
}
$bool = 0;
foreach($items as $item) {
    if($item == $unwantedValue)
    { $bool=1; break; }
}

if($bool==0)
echo 'true';
$equals=true;

foreach($items as $item) {
    if($item!=0)
    {
        $equals=false;
        break;
    }
}
if($equals) {
    echo 'true';
}

if you want to check the values is same with some value in variabel and print it use this

<?php 
$target_check = 7;

$items = array(1, 4, 7, 10, 11);

foreach ($items as $key => $value) {
    if ($value == 7) echo "the value you want is exist in index array of " . $key . '. <br> you can print this value use <br><br> echo $items[' . $key . '];';
}


?>

but if you just want to check the value is exist in array you can use in_array function.

<?php

$target_check = 2;

if (in_array($target_check, $items)) echo "value " . $target_check . 'found in $items';
else echo 'sorry... ' . $target_check . ' is not a part of of $items.';
?>
<?
$items=array(0,1,2,0,3,4);
foreach($items as $item) {
    if($item == 0){ echo "true"; }
}
?>

your code work! check the source of the $items array

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top