Skip to content

Instantly share code, notes, and snippets.

@BaylorRae
Created December 22, 2011 16:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save BaylorRae/1510818 to your computer and use it in GitHub Desktop.
Save BaylorRae/1510818 to your computer and use it in GitHub Desktop.
Short Style for Arrays
<?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;
}
<?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';
@Phobia1971
Copy link

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment