Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP array - remove elements with keys that start with

Tags:

arrays

php

Newbie question - I'm trying to remove elements with keys that start with 'not__'. Its inside laravel project so I (can) use its array functions. I'm trying to remove elements after the loop. This doesn't remove anything, i.e. it doesn't work:

function fixinput($arrinput)
{
    $keystoremove = array();
    foreach ($arrinput as $key => $value);
    {
        if (starts_with($key, 'not__'))
        {
            $keystoremove = array_add($keystoremove, '', $key);
        }
    }
    $arrinput = array_except($arrinput, $keystoremove);
    return $arrinput;
}

Note that it won't be the only task on array. I'll try that myself. :)

Thanks!

like image 219
my2c Avatar asked Jul 03 '13 10:07

my2c


2 Answers

$filtered = array();

foreach ($array as $key => $value) {
    if (strpos($key, 'not__') !== 0) {
        $filtered[$key] = $value;
    }
}
like image 180
deceze Avatar answered Sep 21 '22 00:09

deceze


Using the array_filter function with the ARRAY_FILTER_USE_KEY flag looks to be the best/fastest option.

$arrinput = array_filter( $arrinput, function($key){
    return strpos($key, 'not__') !== 0;
}, ARRAY_FILTER_USE_KEY );

The flag parameters weren't added until version 5.6.0 so for older versions of PHP a for loop would probably be the quickest option.

foreach ($arrinput as $key => $value) {
    if(strpos($key, 'not__') === 0) {
        unset($arrinput[$key]);
    }
}

I would assume the following method is a lot slower but its just a different way of doing it.

$allowed_keys = array_filter( array_keys( $arrinput ), function($key){
    return strpos($key, 'not__') !== 0;
} );
$arrinput = array_intersect_key($arrinput , array_flip( $allowed_keys ));

Function

if(!function_exists('array_remove_keys_beginning_with')){

    function array_remove_keys_beginning_with( $array,  $str ) {

        if(defined('ARRAY_FILTER_USE_KEY')){
            return array_filter( $array, function($key) use ($str) {
                return strpos($key, $str) !== 0;
            }, ARRAY_FILTER_USE_KEY );
        }
        foreach ($array as $key => $value) {

            if(strpos($key, $str) === 0) {
                unset($array[ $key ]);
            }
        }
        return $array;
    }
}
like image 26
TarranJones Avatar answered Sep 19 '22 00:09

TarranJones