Jump to content

Recommended Posts

Recommendations on the best way to extract only specific elements from an array?  What about the following?  Thanks

        while($source=$stmt->fetch(\PDO::FETCH_ASSOC)) {
            if($source['guid']) {
                $clients[]=array_intersect_key($source, ['name'=>null,'guid'=>null]);
            }
            else {
                $servers[]=array_intersect_key($source, ['name'=>null,'ip'=>null,'port'=>null,'encrypt_key'=>null]);
            }
        }
Link to comment
https://forums.phpfreaks.com/topic/302394-extracting-only-specific-array-elements/
Share on other sites

I'd either do that or the obvious solution, mostly depending on whether I remembered about array_intersect_key at the time.

 

Obvious being $clients[]=['name'=>$source['name'],'guid'=>$source['guid']]; with maybe some isset checks?

 

or simply

$clients[] = [ 'name' => $source['name'], 'guid' = $source['guid'] ];

 

You beat me by 1 second!

 

Would you recommend doing it your way if there are only a couple of elements, but using array_intersect_key() if there are more than say 5?

but using array_intersect_key() if there are more than say 5?

You aren't really saving yourself much: still typing out the basic key => value stuff for each element you want.

 

A sort of "array_choose" function would be nice to have built-into PHP. I wouldn't implement it in userland just for this one purpose, though.

/**
 * Extract a subset of an array
 *
 * @param array $array Source array
 * @param array|scalar $key An array of keys, or the first key
 * @param scalar ... Additional keys if $key is not an array
 * @return array
 */
function array_choose(array $array, ...$keys) {
	$return = array();
	foreach (isset($keys[0]) && is_array($keys[0]) ? $keys[0] : $keys as $key) {
		if (array_key_exists($array, $key)) {
			$return[$key] = $array[$key];
		}
	}
	return $return;
}
Edited by requinix
switching out isset for array_key_exists

You could use array_fill_keys to build the second parameter to array_intersect_key easier for larger arrays.

 

if($source['guid']) {
    $clients[]=array_intersect_key($source, array_fill_keys(['name','guid'], null));
}
else {
    $servers[]=array_intersect_key($source, array_fill_keys(['name','ip','port','encrypt_key'], null));
}
  • Like 1
This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.