I
I
Ivan Vasilich2019-12-22 15:22:00
PHP
Ivan Vasilich, 2019-12-22 15:22:00

How to use recursion in closures in php?

good afternoon dear ones.
Here I am conjuring with php and the question arose of how to use recursion in php
, for example, I have a multilevel array and I want to use recursion in a closure.
I try to run the code below in the sandbox and it doesn’t work why, I don’t understand PHP sandbox

<?php

$array = array(
  'row1' => array(
    'row1.1' => 0001.12,
    'row1.2' => false,
    'row1.3' => 0001.12,
  ),
  'row2' => array(
    'row2.1' => 'this is row 2.1',
    'row2.2' => 'this is row 2.2',
  ),
  'row3' => array(
    'row3.1' => 'this is row 3.1',
    'row3.2' => 'not null',
  ),
);

function recursive($input) {

  $closure = function() use (&$input) {
    foreach ($input as $key => $value) {
      if (is_array($value)) {
        $closure();
      } else {
        echo $value;
      }
    }
  }

  $closure();
}

recursive($array);

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2019-12-22
@jcmax

function recursive(&$input) {
  $closure = function(&$input) use (&$closure) {
    foreach ($input as $key => &$value) {
      if (is_array($value)) {
        $closure($value);
      } else {
        echo $value;
      }
    }
  };

  $closure($input);
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question