I can not understand the logic of the code from opencart 2, ...

class Request { public $get = array(); public $post = array(); public $cookie = array(); public $files = array(); public $server = array(); public function __construct() { $this->get = $this->clean($_GET); $this->post = $this->clean($_POST); $this->request = $this->clean($_REQUEST); $this->cookie = $this->clean($_COOKIE); $this->files = $this->clean($_FILES); $this->server = $this->clean($_SERVER); } public function clean($data) { if (is_array($data)) { foreach ($data as $key => $value) { unset($data[$key]); $data[$this->clean($key)] = $this->clean($value); } } else { $data = htmlspecialchars($data, ENT_COMPAT, 'UTF-8'); } return $data; } } 

or rather, this piece ...

 public function clean($data) { if (is_array($data)) { foreach ($data as $key => $value) { unset($data[$key]); $data[$this->clean($key)] = $this->clean($value); } } else { $data = htmlspecialchars($data, ENT_COMPAT, 'UTF-8'); } return $data; } 

    1 answer 1

    This is called a recursive function .

    Meaning: filter all elements in the arrays, regardless of the nesting of the array.

    The condition says: iterate over the elements of the array (multidimensional array) until the final value is different from the array, if the value is not an array, then apply the htmlspecialchars function to the data.

    Imagine that there is an array of data:

     [ 1 => 'test' 2 => ['test1', 'test2'] ] 

    Thanks to this code, all elements (test, test1, test2) will be processed as values ​​and no matter how many arrays will be nested in each other, the htmlspecialchars function will be applied to all array values .

    • Clear! Thanks, and in this part the function causes itself to be obtained? $ data [$ this-> clean ($ key)] = $ this-> clean ($ value); - privetsh
    • Yes, read about recursive functions, understand the whole point. One popular example of using recursive functions is the calculation of Fibanochchi numbers. - Firepro