0

I have an array_filter callback function that checks if digits are in an array like so:

$code = "22";
$orders = array_filter(
            $orders,
            function ($key) use($code) {
                return (in_array($code, $key['trans']));
            }
        );

But this is checking if the trans value has a digit that matches exactly 22, so it's limiting the results.

I'd like to display all trans value's that start with the $code (22) - I'd like to ignore using a for loop if possible, since it'll take longer to display the results.

What can I do instead?

alexel
  • 197
  • 1
  • 1
  • 11

1 Answers1

2

Try changing:

return (in_array($code, $key['trans']));

to

return substr( $key['trans'], 0, strlen($code) ) == $code;

If $key['trans'] is array, then we need to iterate it to search for $code inside it (sandbox example):

return count(array_filter($key['trans'],
  function ($key2) use($code) {
    return substr( $key2, 0, strlen($code) ) == $code;
  })) > 0;

P.S. I used array_filter for inner array because of this answers: find beginning of a string inside an array of strings in php

P.P.S. This is my one-line solution. As @waterloomatt mentioned in comments, simple for is faster than array_filter, so better to create a helper function to check if array has something inside that starts with what you need.

Anton
  • 2,669
  • 1
  • 7
  • 15