I'm running into a dilemma, i'm trying to create a function to "dynamically" search trough an array, in this case my session array, but it should be for any. Now that is not my problem, my problem is to dynamically allow this to be done...
Here's what i have
public static function get($search = 'First/Second/Third') {
$explode = explode('/',$search);
$count = count($explode);
if ($count == 1)
if (isset($_SESSION[$explode[0]]))
return $_SESSION[$explode[0]];
elseif ($count == 2)
if (isset($_SESSION[$explode[0]][$explode[1]]))
return $_SESSION[$explode[0]][$explode[1]];
elseif ($count == 3)
if (isset($_SESSION[$explode[0]][$explode[1]][$explode[2]]))
return $_SESSION[$explode[0]][$explode[1]][$explode[2]];
}
So let's say i have an array:
array('First' => array('Second' => array('Third' => 'TEST VALUE'));
Now i want to call
$value = get('First/Second/Third');
and then get "Test Value" back as the value for my $value variable.
In this situation it works, but it just isn't dynamic, and I want it to be able to handle maybe even a 10 layer deep array as well, without adding more and more lines....
Well maybe someone out here smarter then me :)
Thanks!!
$array = array(
'First' => array(
'Second' => array(
'Third' => 'TEST VALUE'
)
)
);
echo get($array, 'First/Second/Third'); // TEST VALUE
Function Used
function get($data, $part) {
foreach(explode("/", $part) as $key) {
$data = isset($data[$key]) ? $data[$key] : null;
}
return $data;
}
Live Demo
Something like this:
$data = $_SESSION;
foreach(explode('/', $seach) => $pos) {
$data = $data[$pos];
}
return $data;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With