What is and how to use array_walk?

Asked

Viewed 1,033 times

1

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

I couldn’t understand its workings.

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

I stalled because I couldn’t understand this statement:

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

I searched in the PHP manual and I understood the anonymity function receives a parameter and a key: http://php.net/manual/en/function.array-walk.php (example #1).

In the tutorial I am watching the function is only receiving the parameter or would be the key (I don’t understand well). The use serves to access variables outside the scope, but it is not coming from outside the scope, being passed by parameter in public Function run($url), That would already be out of scope?

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

If someone knows how to use array_walk and can explain its use to me tbm, it would help me a lot.

Complete 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);
    }
}

Link Vídeo: https://www.youtube.com/watch?v=o7r1fHI9U4A&index=11&list=PLtxCFY2ITssBl_nihh4HC5-ZlnIPEpVQD

1 answer

2


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

So let’s consider a function that displays twice the numerical value:

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

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

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

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

See working on Ideone.

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

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

array_walk($array, "double");

See working on Ideone.

The difference is basically that the function array_walk does not consider the internal pointer of array, thus ensuring that it is fully traversed in all calls, while the loop foreach only travels the array from the current pointer position 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 cover 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 array and its index. That is, in the example of this answer, the function has only one parameter referring to the value in 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 logic of the function, so more parameters can be defined and will be related to the values in $userdata.

For example, say the function double receive a third parameter which is a multiplier to define the signal, can be 1 or -1. Thus:

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

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

See working on Ideone.

In this case, $signal will receive the value -1.

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

What is the difference between global and superglobal variables?

  • 1

    Congratulations, now I understand. Thank you very much. There was only one question regarding this msg "The difference is basically that the array_walk function does not consider the array’s internal pointer, thus ensuring that it is fully traversed in all calls, while the foreach loop only traverses the array from the position of the current pointer to the end of the array (or a break)" I didn’t understand the difference, because basically it will go through 0...end on array_walk and foreach.

  • 1

    In the first two examples, run next($array) before the foreach and of array_walk and see the difference. The next will move the array’s internal pointer in one position, then the foreach no longer goes through the whole array, but the function array_walk yes.

  • Wow, top rs Thanks buddy :D

  • I have the same problem, I am studying mvc+php with the same course of this question, and in my case although my code is exactly the same as the question, my code does not execute "echo" inside the if. Should I create a new question or can this question be answered here ?

  • 1

    @Gabrielsilva if the code is the same, echo is not executed because the condition is not met.

  • The condition has to be satisfied, because I know the condition and I wrote a route that exists and yet the if did not find it.

  • 1

    @Gabrielsilva then ask a new question and elaborate a [mcve] demonstrating the behavior cited.

  • Some of you might be interested in following the link to my question.https://answall.com/questions/420321/rota-n%C3%a3o-found-php

Show 3 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.