22

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.

6 Answers 6

30
foreach ($array as $subarray)
{
   if(!in_array('hello', $subarray))
   {
      echo 'echo the value';
   }
}
Sign up to request clarification or add additional context in comments.

Comments

11
$attendance = ['present','absent','present','present','present','present'];

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

     echo "student is failed";

  } else {
     
      echo "student is passed";    
   }

Comments

4

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;
}


Comments

2
$isExistHelloInArray = array_filter($array,function($element) {
    return $element['category'] == 'hello';
});

Comments

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

Comments

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';
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.