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. 


<?php
$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

gistfile1.txt

hosted with ❤ by GitHub

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

Hinterlasse einen Kommentar