9

I'm struggling to explain what I want to do here so apologies if I confuse you.. I'm just as confused myself

I have an array like so:

$foo = array(
    array('value' => 5680, 'text' => 'Red'), 
    array('value' => 7899, 'text' => 'Green'), 
    array('value' => 9968, 'text' => 'Blue'), 
    array('value' => 4038, 'text' => 'Yellow'),
)

I want to check if the array contains the value e.g. 7899 and also get the text linked to that value "Green" in the example above.

4
  • 2
    What about foreach()? ... Commented Jul 15, 2014 at 13:48
  • 7899 is not linked to 'yellow'. And exactly what u have to do? Commented Jul 15, 2014 at 13:50
  • @rack_nilesh Apologies for that rack_nilesh.. Addressed that issue. Commented Jul 15, 2014 at 13:52
  • @Phantom I thought about that but I'm already nested within 2 other foreach loops and was wondering if there was a better way of doing so. Commented Jul 15, 2014 at 13:54

3 Answers 3

13

Try something like this

$foo = array(
    array('value' => 5680, 'text' => 'Red'), 
    array('value' => 7899, 'text' => 'Green'), 
    array('value' => 9968, 'text' => 'Blue'), 
    array('value' => 4038, 'text' => 'Yellow'),
);

$found = current(array_filter($foo, function($item) {
    return isset($item['value']) && 7899 == $item['value'];
}));

print_r($found);

Which outputs

Array
(
    [value] => 7899
    [text] => Green
)

The key here is array_filter. If the search value 7899 is not static then you could bring it in to the closure with something like function($item) use($searchValue). Note that array_filter is returning an array of elements which is why I pass it through current

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

1 Comment

Side Note: with dynamic search value $found = current(array_filter($activityArray, function($item) use($jobID) { return isset($item['jobid']) && $jobID == $item['jobid']; })); print_r($found);
4

For PHP >= 5.5.0 it is easier with array_column:

echo array_column($foo, 'text', 'value')[7899];

Or to be repeatable without using array_column each time:

$bar = array_column($foo, 'text', 'value');
echo isset($bar[7899]) ? $bar[7899] : 'NOT FOUND!';

Comments

0

Taking a guess at what you would like here:

function findTextByValueInArray($fooArray, $searchValue){
    foreach ($fooArray as $bar )
    {
        if ($bar['value'] == $searchValue) {
            return $bar['text'];
        }
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.