How to get number of occurrences of a particular Key inside an array in PHP?
Solution:
You can fitler the array elements using the array_filter function:
$jsonStr = '{
"general_rates" : [
{ "id" : 1, "item" : "Item name", "cost1": "", "cost2": "", "cost3": "" },
{ "id" : 2, "item" : "", "cost1": "N/A", "cost2": "N/A", "cost3": 60 }
],
"value1" : "EUROPE",
"value2" : "AMERICA",
"value3" : "FRANCE"
}';
$decoded = json_decode($jsonStr, true);
// Filter the array elements which key start with 'value'
$filtered = array_filter($decoded, function ($key) {
return strpos($key, 'value') === 0;
}, ARRAY_FILTER_USE_KEY);
var_dump(count($filtered));
Answer
Solution:
Use preg_grep and a small regexp "starting with value":
$ar = ['value1', 'value2', 'no_vlue_here', 'and_here'];
$filtered = preg_grep('/^value/', $ar);
echo count($filtered);
Source