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

1

4 Answers 4

4

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

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

2 Comments

I was just editing that, was a typo in the question. The problem is still there.
@Talon let me cook up another answer.
0
foreach ($array as $item) {
    if ($item["Product"] == "Super Amazing Widget") {
        echo "in the array";
        break;
    }
}

Comments

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

Comments

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

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.