0

I have an array in this format:

Array ( [0] => Array ( [NUMBER] => 1 [AMOUNT] => 5 [RATE] => 1 ) [1] => Array ( [NUMBER] => 2 [AMOUNT] => 10 [RATE] => 1 ) [2] => Array ( [NUMBER] => 3 [AMOUNT] => 15 [RATE] => 1 ) )

I can loop thru array and can find the desired result but I am rather looking for some builtin function or function provided by Laravel.

Is there efficient and small way to search this array if it's given two inputs: NUMBER = 3 and AMOUNT = 5 then it returns either true/false or that particular value?

4
  • 1
    What is your expected output? What you have tried so far Post your attempts too? Commented Sep 11, 2015 at 11:32
  • return $arr['NUMBER']==3 && $arr['AMMOUNT']==5; Commented Sep 11, 2015 at 11:32
  • @Uchiha I could loop thru arrays and find values but issue is that some built-in function or function provided by Laravel to perform this job. Commented Sep 11, 2015 at 11:38
  • you could try array_filter, but this function will return a filtered array instead of true/false. Commented Sep 11, 2015 at 11:53

1 Answer 1

1
echo count(
    array_filter(
        $your_array, 
        function ($e) {
            return $e['NUMBER'] == 3 && $e['AMOUNT'] == 5;
        }
    )
);

should do the trick

Test:

$fooArray = array(
    array(
        'NUMBER' => 1,
        'AMOUNT' => 5
    ),
    array(
        'NUMBER' => 2,
        'AMOUNT' => 10,
    ),
    array(
        'NUMBER' => 3,
        'AMOUNT' => 15
    )
);

$barArray = array(
    array(
        'NUMBER' => 1,
        'AMOUNT' => 5
    ),
    array(
        'NUMBER' => 2,
        'AMOUNT' => 10,
    ),
    array(
        'NUMBER' => 3,
        'AMOUNT' => 5
    )
);

echo count(
    array_filter(
        $fooArray, 
        function ($e) {
            return $e['NUMBER'] == 3 && $e['AMOUNT'] == 5;
        }
    )
);
//will echo 0

echo count(
    array_filter(
        $barArray, 
        function ($e) {
            return $e['NUMBER'] == 3 && $e['AMOUNT'] == 5;
        }
    )
);
//will echo 1

If you want the true/false logic, just add a (true == ) or (false == ) test instead of echoing it

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

1 Comment

Short and Sweet. I tried array_intersect but give Array to String Conversion error.

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.