20

I have an array that looks like the following when var_dump:

 array(3) { [0]=> array(3) { ["id"]=> string(1) "3" ["category"]=> string(5) "staff" ["num_posts"]=> string(1) "1" } [1]=> array(3) { ["id"]=> string(1) "1" ["category"]=> string(7) "general" ["num_posts"]=> string(1) "4" } [2]=> array(3) { ["id"]=> string(1) "2" ["category"]=> string(6) "events" ["num_posts"]=> string(1) "1" } }

I need to echo a value if the array does not contain the following string: 'hello'

How is this possible, I have tried using in_array, but unsuccessfully. Help appreciated.

hairynuggets
  • 3,191
  • 22
  • 55
  • 90

6 Answers6

24
foreach ($array as $subarray)
{
   if(!in_array('hello', $subarray))
   {
      echo 'echo the value';
   }
}
Shakti Singh
  • 84,385
  • 21
  • 134
  • 153
10
$attendance = ['present','absent','present','present','present','present'];

if (in_array("absent", $attendance)){

     echo "student is failed";

  } else {
     
      echo "student is passed";    
   }
3

For multi-dimensional array, try:


function in_array_r($needle, $haystack, $strict = true) {
    foreach ($haystack as $item) {
        if (($strict ? $item === $needle : $item == $needle) || (is_array($item) && in_array_r($needle, $item, $strict))) {
            return true;
        }
    }

    return false;
}


Sudhir Bastakoti
  • 99,167
  • 15
  • 158
  • 162
2
$isExistHelloInArray = array_filter($array,function($element) {
    return $element['category'] == 'hello';
});
Anthony
  • 3,218
  • 3
  • 43
  • 73
1

Try this

$array = array( array("id" => "3","category" => "hello" ,"num_posts" =>  "1" ),
    array( "id"=> "1","category"=> "general" ,"num_posts" => "4" ),
    array( "id"=> "2" ,"category"=> "events","num_posts"=>  "1" ));

foreach($array as $value){
    if(!in_array("hello", $value)){
        var_dump($value);
    }
}

its working

Poonam
  • 4,591
  • 1
  • 15
  • 20
0

if you want search in every dimension, try this:

function value_exists($array, $search) {
    foreach($array as $value) {
        if(is_array($value)) {
            if(true === value_exists($value, $search)) {
                return true;
            }
        }
        else if($value == $search) {
            return true;
        }
    }

    return false;
}

if(value_exists($my_array, 'hello')) {
    echo 'ok';
}
else {
    echo 'not found';
}
silly
  • 7,789
  • 2
  • 24
  • 37