Possible Duplicate:
Pattern Match on a Array Key
I need to get all the elements in an array with a specific key pattern. For example in this array:
$items = array(
"a" => "1",
"b" => "2",
"special_1" => "3",
"c" => "4",
"special_2" => "5",
"special_3" => "6",
"d" => "7"
);
I would need all elements with a key containing the string special_
. These should define a new array:
$special_items = array(
"special_1" => "3",
"special_2" => "5",
"special_3" => "6",
);
Is there a smart method besides a while
loop?
The array_keys() function is used to get all the keys or a subset of the keys of an array. Note: If the optional search_key_value is specified, then only the keys for that value are returned. Otherwise, all the keys from the array are returned.
Arrays contains unique key. Hence if u are having multiple value for a single key, use a nested / multi-dimensional array. =) thats the best you got.
Accessing Elements in a PHP Array The elements in a PHP numerical key type array are accessed by referencing the variable containing the array, followed by the index into array of the required element enclosed in square brackets ([]).
Arrays ¶ An array in PHP is actually an ordered map. A map is a type that associates values to keys. This type is optimized for several different uses; it can be treated as an array, list (vector), hash table (an implementation of a map), dictionary, collection, stack, queue, and probably more.
How about this?
$special_items = array();
foreach($items as $key => $val) {
if(substr($key, 0, 8) == 'special_')
$special_items[$key] = $val;
}
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