1

How can I filter an array when a sub element starts with a certain string? This will filter results when 'name' matches 'bk-' but how can I alter it so matched elements starting with 'bk-' instead?

$starts_with = 'bk-';

$new_facets = array_filter($facets, function ($var) use ($starts_with) {
    return ($var['name'] == $starts_with);
});
user2753924
  • 465
  • 1
  • 5
  • 15

2 Answers2

1

Something like substr will do the job, for example:

<?php
$starts_with = 'bk-';

$facets = [
    ['name' => 'bk-0001'],  
    ['name' => 'bk-0002'], 
    ['name' => 'bx-0001']
];

$new_facets = array_filter($facets, function ($var) use ($starts_with) {
    return substr($var['name'], 0, strlen($starts_with)) === $starts_with;
});

print_r($new_facets);

https://3v4l.org/G0bHI

Result:

Array
(
    [0] => Array
        (
            [name] => bk-0001
        )

    [1] => Array
        (
            [name] => bk-0002
        )

)
Lawrence Cherone
  • 46,049
  • 7
  • 62
  • 106
0

Change the function logic:

$new_facets = array_filter($facets, function ($var) use ($starts_with) {
    return (substr($var['name'],0, 3) == $starts_with);
});
Felippe Duarte
  • 14,901
  • 2
  • 25
  • 29