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!
$filtered = array();
foreach ($array as $key => $value) {
if (strpos($key, 'not__') !== 0) {
$filtered[$key] = $value;
}
}
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With