Retain elements in array if associative key starts with specific substring [duplicate]
If I have array like:
array [
y => 35
x => 51
z => 35
c_3 => 4
c_1 => 54
c_6 => 53
c_9 => 52
]
I want to get array of:
array [c_3=>4, c_1=>54, c_6=>53, c_9=>52]
How can I filter out the elements which do not have keys starting with c_
?
Solution 1:
Try this :
$filtred = array();
foreach($yourArray as $key => $value)
if(preg_match('/c_\d/',$key))
$filtred[] = $value;
print_r($filtred);
Solution 2:
Try This
//your array
$arr1 = array (
"y" => 35,
"x" => 51,
"z" => 35,
"c_3" => 4,
"c_1" => 54,
"c_6" => 53,
"c_9" => 52
);
// Array with keys you want
$arr2 = array (
"c_3" => '',
"c_1" => '',
"c_6" => '',
"c_9" => ''
);
//use array_intersect_key to find the common ;)
print_r(array_intersect_key($arr1,$arr2));
Solution 3:
Check this solution with array_filter()
$arr = [
'y' => 35,
'x' => 51,
'z' => 35,
'c_3' => 4,
'c_1' => 54,
'c_6' => 53,
'c_9' => 52,
];
$filtered = array_filter($arr, function($v) use($arr){
return preg_match('#c_\d#', array_search($v, $arr));
});
Solution below will work in PHP >= 5.6.0
$filtered = array_filter($arr, function($k){
return preg_match('#c_\d#', $k);
}, ARRAY_FILTER_USE_KEY);
Both solutions work I've checked them.
Solution 4:
You can try using array_filter()
.
There are some interesting examples on the php documentation page. One of them covers filtering array keys.