note 115006 modified in function.array-intersect-key by cmb

From: Date: Tue, 24 May 2016 14:01:52 +0000
Subject: note 115006 modified in function.array-intersect-key by cmb
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-205579@lists.php.net to get a copy of this message
[Editor's note: changed array_merge_recursive() to array_replace_recursive() to fix the script] Here is a better way to merge settings using some defaults as a whitelist. <?php $defaults = [ 'id' => 123456, 'client_id' => null, 'client_secret' => null, 'options' => [ 'trusted' => false, 'active' => false ] ]; $options = [ 'client_id' => 789, 'client_secret' => '5ebe2294ecd0e0f08eab7690d2a6ee69', 'client_password' => '5f4dcc3b5aa765d61d8327deb882cf99', // ignored 'client_name' => 'IGNORED', // ignored 'options' => [ 'active' => true ] ]; var_dump( array_replace_recursive($defaults, array_intersect_key( $options, $defaults ) ) ); ?> Output: array (size=4) 'id' => int 123456 'client_id' => int 789 'client_secret' => string '5ebe2294ecd0e0f08eab7690d2a6ee69' (length=32) 'options' => array (size=2) 'trusted' => boolean false 'active' => boolean true --was-- Here is a better way to merge settings using some defaults as a whitelist. <?php $defaults = [ 'id' => 123456, 'client_id' => null, 'client_secret' => null, 'options' => [ 'trusted' => false, 'active' => false ] ]; $options = [ 'client_id' => 789, 'client_secret' => '5ebe2294ecd0e0f08eab7690d2a6ee69', 'client_password' => '5f4dcc3b5aa765d61d8327deb882cf99', // ignored 'client_name' => 'IGNORED', // ignored 'options' => [ 'active' => true ] ]; var_dump( array_merge_recursive($defaults, array_intersect_key( $options, $defaults ) ) ); ?> Output: array (size=4) 'id' => int 123456 'client_id' => int 789 'client_secret' => string '5ebe2294ecd0e0f08eab7690d2a6ee69' (length=32) 'options' => array (size=2) 'trusted' => boolean false 'active' => boolean true http://php.net/manual/en/function.array-intersect-key.php

« previous php.notes (#205579) next »