0

I have a simple array of boolean arrays as follows:

array(
    array('dog' => true),
    array('cat' => true),
    array('bird' =>false),
    array('fish' => true)
)

How can I find an entry, such as 'cat', without a loop construct? I think I should be able to accomplish this with a php array function, but the solution is eluding me! I just want to know if 'cat' is a valid key - I'm not interested in it's value.

In the example above, 'cat' should return true, while 'turtle' should return false.

1
  • 3
    Why are you scared of a loop? Easy solution there... Commented Jan 20, 2014 at 4:55

2 Answers 2

1
$array = array(
  array('dog' => true),
  array('cat' => true),
  array('bird' =>false),
  array('fish' => true)
);

array_walk($array,'test_array');

function test_array($item2, $key){
$isarray =  is_array($item2) ? 'Is Array<br>' : 'No array<br>';
echo $isarray;
}

using array_walk example in the manual

Output:

Is Array
Is Array
Is Array
Is Array

Ideone

Sign up to request clarification or add additional context in comments.

1 Comment

Doesn't answer OP question. How does turtle fit into this answer?
1


You could achieve it like this :

  1. Reduce your array to a single dimensional array using combination of array_reduce and array_merge PHP functions .
  2. In the reduced array , look for the key using array_key_exists .

Your array :

$yourArray = array
(
     array( 'dog' => true )
    ,array( 'cat' => true )
    ,array( 'bird' =>false )
    ,array( 'fish' => true )
);

Code to check if a key exists :

$itemToFind = 'cat'; // turtle

$result =
    array_key_exists
    (
         $itemToFind
        ,array_reduce(
             $yourArray
            ,function ( $v , $w ){ return array_merge( $v ,$w ); }
            ,array()
        )
    );

var_dump( $result );

Code to check if a key exits and to retrieve its value :

$itemToFind = 'cat'; // bird

$result =
    array_key_exists
    (
        $itemToFind
        ,$reducedArray = array_reduce(
            $yourArray
            ,function ( $v , $w ){ return array_merge( $v ,$w ); }
            ,array()
        )
    ) ?$reducedArray[ $itemToFind ] :null;

var_dump( $result );

Using PHP > 5.5.0

You could use combination of array_column and count PHP functions to achieve it :

Code to check if a key exists :

$itemToFind = 'cat';    // turtle

$result = ( count ( array_column( $yourArray ,'cat' ) ) > 0 ) ? true : false;

var_dump( $result );

The above code tested with PHP 5.5.5 is here

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.