Mustapha
Mustapha

Reputation: 101

Determine if any row in a 2d array has a qualifying column value

I have this array:

$fruits = [
    ['name' => 'banana', 'color' => 'yellow' , 'shape' => 'cylinder'],
    ['name' => 'apple', 'color' => 'red' , 'shape' => 'sphere'],
    ['name' => 'orange', 'color' => 'orange' , 'shape' => 'sphere'], 
];

How can I find out if the array $fruits already contains apple in it?

I have tried: in_array("apple", $fruits) and that didn't work out.

I also tried various syntax and messed a bit with array_key_exists(), but nothing worked out. Any ideas?

Upvotes: -1

Views: 164

Answers (8)

mickmackusa
mickmackusa

Reputation: 47764

From PHP8.4, PHP is no longer "notoriously unwieldy" for tasks when short-circuiting array searching is desired. Demo

  1. Is there at least one qualifying value (row)? Call array_any().

    var_export(
        array_any(
            $fruits,
            fn($row) => $row['name'] === 'apple'
        )
    );
    // true
    
  2. Do all values (rows) qualify? Call array_all().

    var_export(
        array_all(
            $fruits,
            fn($row) => $row['name'] === 'apple'
        )
    );
    // false
    
  3. Want the first level key of the first occurring qualifying value (row)? Call array_find_key().

    var_export(
        array_find_key(
            $fruits,
            fn($row) => $row['name'] === 'apple'
        )
    );
    // 1
    
  4. Want the whole value (row) of the first qualifying value (row)? Call array_find().

    var_export(
        array_find(
            $fruits,
            fn($row) => $row['name'] === 'apple'
        )
    );
    /*
    array (
        'name' => 'apple',
        'color' => 'red',
        'shape' => 'sphere',
    )
    */
    

All of these functions are optimized for performance so that developers no longer need to write a conditionally broken loop.

Upvotes: 0

curious_coder
curious_coder

Reputation: 2458

foreach($fruits as $fruit)
{ 
    /*In first loop $fruit = array('name'=>'banana', 'color'=>'yellow' ,
      'shape'=>'cylinder')
    */
    if(in_array("apple",$fruit))
    {
       /*Using in_array() function we don't have to worry about array keys. 
         The function checks whether the value exists in given array.
         Returns TRUE if value is found in the array, FALSE otherwise.
         if(in_array("apple",$fruit)) checks for TRUE
       */

       //Do something
    }
}

in_array(): http://php.net/manual/en/function.in-array.php
foreach(): http://php.net/manual/en/control-structures.foreach.php

Upvotes: 1

Ryan Mortensen
Ryan Mortensen

Reputation: 2327

$hasapple = 0;
foreach($fruits as $keynum)
{
    foreach($keynum as $fruitinfokey => $value)
        {
        if($value == "apple")
            {
            echo "fruits contains " . $value;
            $hasapple = 1;
            }
}
}

if($hasapple == 0)
    {
    echo "The array $fruits does not contain apple";
    }

Put a foreach loop inside of another foreach loop to search through expanded keys.

Upvotes: 0

Manish Jangir
Manish Jangir

Reputation: 505

    function arraySearch($value, $array) {
       foreach ($array as $key => $val) {
           if ($val['name'] === $value) {
               return true;
           }
       }
       return null;
    }

if(arraySearch('apple',$fruits)){
   echo "yes found";
}else{
   echo "not found";
}

Upvotes: 0

furas
furas

Reputation: 142631

<?php

$fruits = array(
    array('name'=>'banana', 'color'=>'yellow' , 'shape'=>'cylinder'),
    array('name'=>'apple', 'color'=>'red' , 'shape'=>'sphere'),
    array('name'=>'orange', 'color'=>'orange' , 'shape'=>'sphere') 
);

$result = false;

foreach($fruits as $subarray) {
    if( in_array('apple', $subarray) ) {
        $result = true;
        break;
    }
}

echo "result is ", ($result ? "TRUE" : "FALSE");

?>

Upvotes: 1

bwoebi
bwoebi

Reputation: 23777

$hasApple = false;
foreach ($fruits as $subArray) {
    if ($subArray['name'] == "apple")
        $hasApple = true;
}

This is the normal solution, simple. You can also try with array_map($fruits, function () use (&$hasApple) { /* ... */ }). (but this may be slower...)

As of PHP 5.5 there is an one-liner possible:

$hasApple = in_array("apple", array_column($fruits, "name"));

Upvotes: 1

Vijaya Pandey
Vijaya Pandey

Reputation: 4282

Try this:

 <?PHP


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

    return false;
}

$b = array(array('name'=>'banana', 'color'=>'yellow' , 'shape'=>'cylinder'), array('name'=>'apple', 'color'=>'red' , 'shape'=>'sphere'),array('name'=>'orange', 'color'=>'orange' , 'shape'=>'sphere'));
echo in_array_r("apple", $b) ? 'found' : 'not found';

?>

Codepad Demo>>

Upvotes: 0

Jon
Jon

Reputation: 437326

PHP is notoriously unwieldy in such cases. The best all-around solution is a simple foreach:

$found = false;
foreach ($fruits as $fruit) {
    if ($fruit['name'] == 'apple') {
        $found = true;
        break;
    }
}

if ($found) ....

You can write this in a number of sexier ways, but all of them will require additional memory allocation and/or will be slower; a good number of them will also be more difficult to understand if you are not very experienced.

Upvotes: 3

Related Questions