Magic Lasso
Magic Lasso

Reputation: 1542

Get array value using a string as the array name and indexes

I am trying to send specific indexes from arrays by string to some php code to describe the data that I need to combine. The problem I am having is that SESSION does not seem to be available within the function Str_To_Array. What am I missing about scope here? Also if anybody can recommend a better way I would be every so grateful. PS i added the include in case including the function causes any abnormalities.

function Str_To_Array($str) {

    $d = explode(':',$str) ;

    print_r($d[0]) ;

    $t = $d[0] ;

    $n = $$t ;

    if( !isset( $d[1] ) ) { return $n ; }

    $n = $n[$d[1]] ;

    return $n ;
}

include(DIR_ROOT . "php_function/Str_To_Array.php") ;

$test = '_SESSION' ;
$ARRANGE = Str_To_Array($test) ;<----this says _SESSION is undefined
print_r($ARRANGE) ;
$ARRANGE = $$test ;<----this works
print_r($ARRANGE) ;

Upvotes: 1

Views: 126

Answers (2)

xdazz
xdazz

Reputation: 160853

It loos like it's the problem of PHP, just tried the code below, when in a function, ${'_SESSION'} works and $$t don't work. This only happens to $_SESSION but not the other super global $_POST and $_GET etc.

<?php
session_start();

function foo() {
  $t = '_SESSION';
  $a = $$t;             // not work
  $b = ${'_SESSION'};   // works
  var_dump($a, $b);
}

foo();

Upvotes: 1

Crisp
Crisp

Reputation: 11447

Hard to follow the purpose here, however this should work

function getVar($str)
{
    $vars = get_defined_vars();
    $d = explode(':',$str) ;
    if (isset($vars[$d[0]]) || array_key_exists($vars[$d[0]])) {
        if (!empty($d[1]) && (isset($vars[$d[0]][$d[1]]) || array_key_exists($vars[$d[0]][$d[1]]))
            return $vars[$d[0]][$d[1]];
        return $vars[$d[0]];
    }
    return null;
}

Upvotes: 0

Related Questions