Created
December 22, 2011 16:07
-
-
Save BaylorRae/1510818 to your computer and use it in GitHub Desktop.
Short Style for Arrays
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Used for searching nested arrays | |
* Instead of `$user['profile']['avatar']['large']` | |
* It allows for `search_params($user, 'profile.avatar.large') | |
* | |
* Benefits | |
* - It checks if the value is set. if not returns null | |
* - makes sure the array is there. | |
* | for instance, what if an API changes | |
* | |
* @param string $haystack | |
* @param string $needle | |
* @return void | |
* @author Baylor Rae' | |
*/ | |
function search_params($haystack, $needle) { | |
$keys = explode('.', $needle); | |
$output = $haystack; | |
$changed = false; | |
foreach( $keys as $key ) { | |
if(isset($output[$key])){ | |
$output = $output[$key]; | |
$changed = true; | |
// End of array chain? | |
if( !is_array($output) ) | |
break; | |
}else { // no matches? no results | |
$changed = false; | |
break; | |
} | |
} | |
return $changed ? $output : null; | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function _post($needle) { | |
return search_params($_POST, $needle); | |
} | |
function _get($needle) { | |
return search_params($_GET, $needle); | |
} | |
// Usage | |
$username = _post('user.username') || false; | |
$thumbnail = _post('user.profile.thumbnail.large') || 'default.png'; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I used a simular appraoch to get data from an array, but i was wondering do you have an idea to use the same approach to change the data in a array.