Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array reduce assinging variable ouside the function

Tags:

php

I want to flatten multidimensional array to single dimensional so I use array_reduce() to get it done. But struck in this place.

$array = array
            (
                1 => array
                    (
                        0 => 1,
                        1 => 'a'                 
                    ),

                2 => array
                    (
                        0 => 2,
                        1 => 'b'                 
                    )
            )

Code :

$key = 1;   
$array_reduced = array_reduce( $array,function(&$result, $item){    
                        $result[] = $item[$key];
                        return $result;                                 
                        }); 
print_r($array_reduced);    

Output Should be :

 Array
 (
     [0] => a

     [1] => b
 )

Which shows Undefined variable: key in this line $result[] = $item[$key]; If I replace the $item[$key] to $item[1] its working.

How to use $key in array_reduce().

like image 281
Raja Avatar asked May 01 '26 01:05

Raja


1 Answers

Well your problem is simply that the variable $key is out of scope in the closure function. So you could either use the keyword global (which isn't the nicest) or use(). So I would recommend you to use use() like this:

array_reduce($array, function(&$result, $item)use($key){  //<-- See use
    $result[] = $item[$key];
    $key++;  //Don't forget to increment your variable
    return $result;
}); 
like image 157
Rizier123 Avatar answered May 02 '26 15:05

Rizier123