What is and how to use array_walk?

1

I'm learning about mvc through a series of video lessons on youtube, so that's fine, but the guy came to a point that ended up using array_walk ().

I could not understand how it works.

The full code is this + down and the video is on the link soon after (4 min video only). More ahead, it is getting the url that the user is trying to access and then checking on the routes already defined.

I crashed because I could not understand this statement:

array_walk($this->routes, function($route) use($url) {
    ...
}

I searched the PHP manual and as far as I understand the anonymous function it gets a parameter and a key: link (example # 1).

In the tutorial I'm watching the function is only receiving the parameter or would be the key (I did not quite understand). The use is used to access variables outside the scope, but it is not coming from outside the scope, being passed by parameter in public function run $ url) , would that already be out of scope?

array_walk(array, function(parametro/chave?) use(fora escopo?) {
    ...
}

Your someone knows how to use the array_walk and can explain their usage to me, it would help me a lot.

Full Code:

namespace app;

class Init
{
    private $routes;

    //Construtor
    public function __construct()
    {
        $this->initRoutes();
        $this->run($this->getUrl());
    }

    //Criando Rotas
    public function initRoutes()
    {
        $ar['home'] = array('route'=>'/', 'controller'=>'index', 'action'=>'index');
        $ar['empresa'] = array('route'=>'/empresa', 'controller'=>'index', 'action'=>'empresa');
        $this->setRoutes($ar);
    }

    //Rotas
    public function run($url)
    {
        array_walk($this->routes, function($route) use($url) {
            if($url == $route['route']) {
                echo "encontrou!!!";
            }
        });
    }

    //Setando rotas na variavel $routes
    public function setRoutes(array $routes)
    {
        $this->routes = $routes;
    }

    //Pegando url q usuario esta tentando acessar
    public function getUrl()
    {
        return parse_url($_SERVER['REQUEST_URI'],PHP_URL_PATH);
    }
}

Video link: link

    
asked by anonymous 28.09.2017 / 04:12

1 answer

3

The function array_walk is used to apply a given function to all values of an array . It is easier to understand if we initially do not consider an anonymous function.

So let's consider a function that displays double the numeric value:

function double($x) {
    echo 2*$x, PHP_EOL;
}

If we wanted to display double the values of an array , we could do:

$array = [1, 2, 3, 4];

foreach ($array as $x) {
    double($x);
}
  

See working at Ideone .

Or use the array_walk function, which, for practical purposes, will be equivalent to foreach :

$array = [1, 2, 3, 4];

array_walk($array, "double");
  

See working at Ideone .

The difference is basically that the array_walk function does not consider the internal pointer of the array , thus ensuring that it is fully traversed in all calls, whereas the foreach loop only traverses the array from the position of the current pointer to the end of the array (or a break

The syntax of the function is:

bool array_walk ( array &$arrary , string $funcname [, mixed $userdata ] )
  • $array is the array that we want to go through and apply the function;
  • $funcname is the name of the function that will be executed (or an anonymous function);
  • $userdata are additional parameters that will be passed to $funcname ;

The function defined by $funcname normally receives two parameters: the value present in the array and its index. That is, in the example of this answer, the function has only one parameter referring to the value in the array . The index is ignored. The same occurs in the example quoted in the question. However, not always these two parameters, value and index, are sufficient for the function logic, then more parameters can be defined and will be related to the values in $userdata .

For example, let's say that the double function receives a third parameter that is a multiplier to set the signal, which can be 1 or -1. So:

function double($value, $key, $signal) {
    echo 2*$signal*$value, PHP_EOL;
}

$array = [1, 2, 3, 4];
array_walk($array, "double", -1);
  

See working at Ideone .

In this case, $signal will get -1.

The same goes for anonymous functions, as exemplified in the question. The behavior is exactly the same. As for doubt about use , yes use is for you to import an external variable for the scope of the anonymous function. Even if the variable is set as a parameter in the method where the array_walk is being called, it will still not be naturally within the scope of the anonymous function and therefore need to import it. Note that in PHP global variables are not imported into local scopes automatically - only superglobal variables have this behavior.

What's the difference between global and superglobal variables?

    
28.09.2017 / 04:57