简体   繁体   中英

Compare Array key value with the given name

Hi i am working on some array operations with loop.

I want to compare array key value with the given name.

But i am unable to get exact output.

This is my array :

Array
(
    [0] => Array
        (
            [label] =>  
            [value] => 
        )

    [1] => Array
        (
            [label] => 3M
            [value] => 76
        )

    [2] => Array
        (
            [label] => Test
            [value] => 4
        )

    [3] => Array
        (
            [label] => Test1
            [value] => 5
        )

    [4] => Array
        (
            [label] => Test2
            [value] => 6
        )
)

This is my varriable which i need to compare : $test_name = "Test2";

Below Code which i have tried :

 $details // getting array in this varriable
if($details['label'] == $test_name)
{
    return $test_name;
}
else
{
    return "NotFound";
}

But every time its returns NotFound.

Not getting what exactly issue.

@Manthan Dave try with array_column and in_array() like below:

<?php
if(in_array($test_name, array_column($details, "label"))){
    return $test_name;
}
else
{
    return "NotFound";
}

$details is a multidimensional array, but you are trying to access it like a simple array.
You need too loop through it:

foreach ($details as $item) {
    if($item['label'] == $test_name)
    {
        return $test_name;
    }
    else
    {
        return "NotFound";
    }
}

I hope your array can never contain a label NotFound ... :)

You have array inside array try with below,

if($details[4]['label'] == $test_name)
{
    return $test_name;
}
else
{
    return "NotFound";
}

Although foreach loop should work but if not try as,

for($i=0; $i<count($details); $i++){

    if($details[$i]['label'] == $test_name)
    {
        return $test_name;
    }
    else
    {
        return "NotFound";
    }

}

Just use in_array and array_column without use of foreach loop as

if (in_array($test_name,array_column($details, 'label')))
{
    return $test_name;
}
else
{
    return "NotFound";
}

You need to check only the if condition like below because else meet at first time it will return the "notfound" then it will not execute.

$result = 'NotFound';
foreach ($details as $item) {
    if($item['label'] == $test_name)
    {
        $result = $test_name;
    }
}
return $result;

or

$result = 'NotFound';
if (in_array($test_name,array_column($details, 'label')))
{
    $result = $test_name;
}
return $result;

这样遍历数组,

array_walk($array, function($v) use($test_name){echo $v['label'] == $test_name ? $test_name : "NotFound";});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM