2

I checked several similar questions like this, this, and this but remain not clear that, can I get a firm value by operations inside a deep nested array, rather than calling function or assigning a variable?

As an example below to insert at the first position of $arr['row'] depending on $s:

$s = true; //or false; 
$arr = [
  'key1'=>'val1', 
  'key2'=>'val2', 
  'row'=>[
    function($s){
      if($s) return array('x'=>'y',...); 
      else return null; 
    }, 
    [
      'row2a'=>'val2a', 
      'row2b'=>'val2b', 
    ], 
    [
      'row3a'=>'val3a', 
      'row3b'=>'val3b', 
    ], 
  ], 
]; 

// Output: 
Array(
    ...
    [row] => Array
    (
        [0] => Closure Object
            (
                [parameter] => Array
                    (
                        [$s] => 
                    )
            )
        [1] => Array
            (
                [row2a] => val2a
                [row2b] => val2b
            )    
    ...

got Closure Object not array('x'=>'y',...) in $arr['row'][0]. Or it's no way to get value by operations inside an array, but calling function or passing by variables? Thanks.

Community
  • 1
  • 1
James
  • 691
  • 5
  • 10
  • I am not sure why can't you simply execute this function outside of the array creation and just put the result where you need it? Is there any particular reason you want to have such construct? – Aleksander Wons May 17 '16 at 06:13
  • It's been in a function and I have some more places like this, means I'd need to create more functions outside just few code to get the values.. – James May 17 '16 at 06:18

2 Answers2

1

If this is what you need you can always try this approach:

$s = 1; 
$value = call_user_func(function($s) { return $s; }, $s);

var_dump($value);

And it will produce:

int(1)
Aleksander Wons
  • 3,611
  • 18
  • 29
0
Try below code
$s=true;

function abc($flag) {
    if ($flag):
        $array["x"]="x";
        $array["y"]="y";
        return $array;
    else:
        return null;
    endif;
}
$arr = [
    'key1' => 'val1',
    'key2' => 'val2',
    'row' => [
        $resultset = abc($s),
        [
            'row2a' => 'val2a',
            'row2b' => 'val2b',
        ],
        [
            'row3a' => 'val3a',
            'row3b' => 'val3b',
        ],
    ],
];
print_r($arr);
exit; 
output
Array
(
    [key1] => val1
    [key2] => val2
    [row] => Array
        (
            [0] => Array
                (
                    [x] => x
                    [y] => y
                )

            [1] => Array
                (
                    [row2a] => val2a
                    [row2b] => val2b
                )

            [2] => Array
                (
                    [row3a] => val3a
                    [row3b] => val3b
                )
        )
)