Find subset of associative array in PHP

This is a simple way to get a subset of associative array elements using an array of keys; basically you extract out the elements you want from a bigger array by listing the keys you need. 

$associative_array = ['firstname' => 'John', 'lastname' => 'Smith', 'DOB' => '2000-10-10', 'country' => 'Ireland' ];
$subset = array_intersect_key( $associative_array, array_flip( [ 'lastname', 'country' ] ) );
print_r( $subset );
// Outputs…
// Array ( [lastname] => Smith [country] => Ireland );

view raw


hosted with ❤ by GitHub

I have come by this before when searching an associative array using a wildcard.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s