1

I have an array that looks like this:

Array
(
[0] => Array
(
    [Product] =>  Amazing Widget
    [Value] => 200
)

[1] => Array
(
    [Product] => Super Amazing Widget
    [Value] => 400
)

[2] => Array
(
    [Product] =>  Promising Widget 
    [Value] => 300
)

[3] => Array
(
    [Product] => Superb Widget
    [Value] => 400
)
)

I believe it's a nested Multi-dimensional array.

Anyway I'm trying to detect if a Product Name Already exists in the array. This is what I'm trying to do

if('Super Amazing Widget' is in the array) {
    echo 'In the Array';
}

I've tried this:

if(in_array('Super Amazing Widget', $array)){
    echo 'In The Array';
}

But it's not working and I can't find out why.

EDIT:

Some of the Functions in here worked really well: in_array() and multidimensional array

Community
  • 1
  • 1
Talon
  • 4,937
  • 10
  • 43
  • 57
  • 1
    `in_array` won't work the way you want on this array, see http://stackoverflow.com/questions/4128323/in-array-and-multidimensional-array – John Flatness Apr 16 '12 at 20:04

4 Answers4

5

in_array will not do a recursive search, ie, search in sub-arrays. You'll need to loop through your array and manually check for your value.

$found = false;
foreach($arr as $item) {
    if ($item['Product'] == 'Super Amazing Widget') {
        $found = true;
        break;
    }
}
if ($found)
    echo 'found!'; //do something

Live example

Alex Turpin
  • 46,743
  • 23
  • 113
  • 145
0
foreach ($array as $item) {
    if ($item["Product"] == "Super Amazing Widget") {
        echo "in the array";
        break;
    }
}
kuba
  • 7,329
  • 1
  • 36
  • 41
0

This is without using a loop:

$filt = array_filter($array, create_function('$val',
                                'return $val["Product"] === "Super Amazing Widget";'));
if (!empty($filt)) {
    echo "In The Array\n";
}
anubhava
  • 761,203
  • 64
  • 569
  • 643
0

using array_filter similar to a previous answer, but using the newer anonymous function instead of the older create_function():

if(array_filter(
    $array, 
    function($val) { return $val['Product'] === 'Super Amazing Widget'; }
    )) {
    echo 'In the array' . PHP_EOL;
}
Clay Hinson
  • 932
  • 1
  • 6
  • 9