PHP array - delete items with keys that start with

Question with a beginner. I am trying to remove items with keys starting with "not__". His internal project is laravel, so I (can) use its array functions. I am trying to remove items after a loop. This does not delete anything, i.e. Does not 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 this will not be the only task in the array. I will try it myself. :)

Thanks!

+4
source share
4 answers
 $filtered = array(); foreach ($array as $key => $value) { if (strpos($key, 'not__') !== 0) { $filtered[$key] = $value; } } 
+4
source

Using array_filter with the ARRAY_FILTER_USE_KEY flag looks like the best / fastest option.

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

Flag options were not added before version 5.6.0, so for older versions of PHP, a for loop would probably be the fastest option.

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

I would suggest that the following method is much slower, but this is just another way to do this.

 $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; } } 
+1
source

Some PHP regex fu:

 $array = array('not__foo' => 'some_data', 'bar' => 'some_data', 12 => 'some_data', 15 => 'some_data', 'not__taz' => 'some_data', 'hello' => 'some_data', 'not__world' => 'some_data', 'yeah' => 'some_data'); // Some data $keys = array_keys($array); // Get the keys $filter = preg_grep('#^not__#', $keys); // Get the keys starting with not__ $output = array_diff_key($array, array_flip($filter)); // Filter it print_r($output); // Output 

Output

 Array ( [bar] => some_data [12] => some_data [15] => some_data [hello] => some_data [yeah] => some_data ) 
0
source

Try it...

 function fixinput($arrinput) { $keystoremove = array(); foreach ($arrinput as $key => $value); { if (preg_match("@^ not__@ ",$key)) { $keystoremove = array_add($keystoremove, '', $key); } } $arrinput = array_except($arrinput, $keystoremove); return $arrinput; } 
-1
source

Source: https://habr.com/ru/post/1489451/


All Articles