Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get only the array elements with certain keys [duplicate]

Tags:

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?

like image 308
Steeven Avatar asked Oct 14 '12 22:10

Steeven


People also ask

How do you find the specific value of a key in an array?

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.

Can array have duplicate keys?

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.

How to access PHP array elements?

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 ([]).

What is array[] PHP?

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.


1 Answers

How about this?

$special_items = array();

foreach($items as $key => $val) {
    if(substr($key, 0, 8) == 'special_')
        $special_items[$key] = $val;
}
like image 173
Austin Brunkhorst Avatar answered Oct 11 '22 09:10

Austin Brunkhorst