Home > Software design >  PHP Check if in array an specific value is true
PHP Check if in array an specific value is true

Time:09-29

Can someone help me out.

I'm looking for an solution how to check if in $testArray there is an array with ['value']['content'] == 1

I have tried:

$bool = in_array('1', array_column($testArray, 'content'));
var_dump($bool);

But than I get an return FALSE, but if you take a look at the testArray below you see the first array has ['value']['content'] => '1';

<?php

        $testArray = array(
            array(
                'id' => '414-b9108bbe-66e3-4c1e-8a51-03b7b8a0d17c',
                'position' => 0,
                'type' => 'original',
                'value' => array
                    (
                        'comment' => '',
                        'content' => '1',
                        'info' => '',
                        'insight' => '',
                        'label' => '',
                        'report' => '',
                    )

            ),
            array(
                'id' => '414-b9108bbe-66e3-4c1e-8a51-03b7b8a0d18c',
                'position' => 0,
                'type' => 'original',
                'value' => array
                    (
                        'comment' => '',
                        'content' => '',
                        'info' => '',
                        'insight' => '',
                        'label' => '',
                        'report' => '',
                    )

            ),
        );

        echo '<pre>';
        $bool = array_search('content', array_column($testArray, 'value'));
        var_dump($bool);
        echo '</pre>';

I think its because of the value is an other Array because i do:

$bool = in_array('original', array_column($testArray, 'type'));

Output: true.

CodePudding user response:

You can try this. (Sorry for my bad english,hope you can understand)

// This is a two-dimensional array, you only need to do the array_column operation once more
var_dump(in_array('1', array_column(array_column($testArray, 'value'), 'content')));

CodePudding user response:

Try as below simple you can find any value from your array

function searcharray($value, $key, $array) {
    
   foreach ($array as $k => $val) {
       if ($val[$key] == $value) {
           foreach ($val as $k1 => $val1) {
               if ($val1[$key] == $value) {
                   return true;
               }
           }
           return true;
       }else{
           foreach ($val as $k1 => $val1) {
               if ($val1[$key] == $value) {
                   return true;
               }
           }
           
       }
   }
   return false;
}

var_dump(searcharray('0','position',$testArray));`enter code here`

  • Related