Remove all elements from array that do not start with a certain string

PhpArraysKeyFilteringArray Filter

Php Problem Overview


I have an array that looks like this:

array(
  'abc' => 0,
  'foo-bcd' => 1,
  'foo-def' => 1,
  'foo-xyz' => 0,
  // ...
)

How can I retain only the elements that start with foo-?

Php Solutions


Solution 1 - Php

Functional approach:

$array = array_filter($array, function($key) {
    return strpos($key, 'foo-') === 0;
}, ARRAY_FILTER_USE_KEY);

Procedural approach:

$only_foo = array();
foreach ($array as $key => $value) {
    if (strpos($key, 'foo-') === 0) {
        $only_foo[$key] = $value;
    }
}

Procedural approach using objects:

$i = new ArrayIterator($array);
$only_foo = array();
while ($i->valid()) {
    if (strpos($i->key(), 'foo-') === 0) {
        $only_foo[$i->key()] = $i->current();
    }
    $i->next();
}

Solution 2 - Php

This is how I would do it, though I can't give you a more efficient advice before understanding what you want to do with the values you get.

$search = "foo-";
$search_length = strlen($search);
foreach ($array as $key => $value) {
    if (substr($key, 0, $search_length) == $search) {
        ...use the $value...
    }
}

Solution 3 - Php

Simply I used array_filter function to achieve the solution as like follows

<?php

$input = array(
    'abc' => 0,
    'foo-bcd' => 1,
    'foo-def' => 1,
    'foo-xyz' => 0,
);

$filtered = array_filter($input, function ($key) {
    return strpos($key, 'foo-') === 0;
}, ARRAY_FILTER_USE_KEY);

print_r($filtered);

Output

Array
(
    [foo-bcd] => 1
    [foo-def] => 1
    [foo-xyz] => 0
)

For live check https://3v4l.org/lJCse

Solution 4 - Php

From PHP 5.3 you can use the preg_filter function: here

$unprefixed_keys = preg_filter('/^foo-(.*)/', '$1', array_keys( $arr ));

// Result:
// $unprefixed_keys === array('bcd','def','xyz')

Solution 5 - Php

$arr_main_array = array('foo-test' => 123, 'other-test' => 456, 'foo-result' => 789);

foreach($arr_main_array as $key => $value){
    $exp_key = explode('-', $key);
    if($exp_key[0] == 'foo'){
         $arr_result[] = $value;
    }
}

if(isset($arr_result)){
    print_r($arr_result);
}

Solution 6 - Php

foreach($arr as $key => $value)
{
   if(preg_match('/^foo-/', $key))
   {
        // You can access $value or create a new array based off these values
   }
}

Solution 7 - Php

Modification to erisco's Functional approach,

array_filter($signatureData[0]["foo-"], function($k) {
    return strpos($k, 'foo-abc') === 0;
}, ARRAY_FILTER_USE_KEY);

this worked for me.

Solution 8 - Php

In addition to @Suresh Velusamy's answer above (which needs at least PHP 5.6.0) you can use the following if you are on a prior version of PHP:

<?php

$input = array(
    'abc' => 0,
    'foo-bcd' => 1,
    'foo-def' => 1,
    'foo-xyz' => 0,
);

$filtered = array_filter(array_keys($input), function($key) {
    return strpos($key, 'foo-') === 0;
});

print_r($filtered);

/* Output:
Array
(
    [1] => foo-bcd
    [2] => foo-def
    [3] => foo-xyz
)
// the numerical array keys are the position in the original array!
*/

// if you want your array newly numbered just add:
$filtered = array_values($filtered);

print_r($filtered);

/* Output:
Array
(
    [0] => foo-bcd
    [1] => foo-def
    [2] => foo-xyz
)
*/

Solution 9 - Php

From PHP5.6, the array keys can be the sole subject of the filtration by using the ARRAY_FILTER_USE_KEY constant/flag.

From PHP7.4, arrow functions make custom functions more concise and allow values to be passed into the custom function's scope without use().

From PHP8, str_starts_with() can take the place of strpos(...) === 0

Code: (Demo)

$array = [
  'abc' => 0,
  'foo-bcd' => 1,
  'foo-def' => 1,
  'foo-xyz' => 0,
];

$prefix = 'foo';

var_export(
    array_filter(
        $array,
        fn($key) => str_starts_with($key, $prefix),
        ARRAY_FILTER_USE_KEY
    )
);

Output:

array (
  'foo-bcd' => 1,
  'foo-def' => 1,
  'foo-xyz' => 0,
)

Solution 10 - Php

You might pass a key-value single dimensional array and a specific prefix string 'foo-' to the function just made: filter_array_key_with_prefix

<?php

function filter_array_key_with_prefix($arr, $prefix) {
  return array_filter($arr, function($k) use ($prefix) {
    return strpos($k, $prefix) === 0;
  }, ARRAY_FILTER_USE_KEY);
}

$arr = array(
  'abc' => 0,
  'foo-bcd' => 1,
  'foo-def' => 1,
  'foo-xyz' => 0,
  // ...
);

$filtered = filter_array_key_with_prefix($arr, 'foo-');

var_dump($filtered);

Output:

array(3) {
  ["foo-bcd"]=>
  int(1)
  ["foo-def"]=>
  int(1)
  ["foo-xyz"]=>
  int(0)
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAlexView Question on Stackoverflow
Solution 1 - PhperiscoView Answer on Stackoverflow
Solution 2 - Phpuser613857View Answer on Stackoverflow
Solution 3 - PhpSuresh VelusamyView Answer on Stackoverflow
Solution 4 - PhpbiziclopView Answer on Stackoverflow
Solution 5 - PhpDeveloper-SidView Answer on Stackoverflow
Solution 6 - PhpTim CooperView Answer on Stackoverflow
Solution 7 - PhpKeyurView Answer on Stackoverflow
Solution 8 - PhpNetsurferView Answer on Stackoverflow
Solution 9 - PhpmickmackusaView Answer on Stackoverflow
Solution 10 - PhpmondayrrisView Answer on Stackoverflow