1

i have this array

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

and this function

function change($array) {
    foreach ($array as $key => $value) {
        $form[$key+5][$value-1] = $key-$value;
    }
    return $form;
}
change($array);

in it the form that i want to rearrange the array in is $form[$key+5][$value-1] = $key-$value; but i want to make it defined by a parameter like this

function change($array, $form) {
    foreach ($array as $key => $value) {
        $form;
    }
    return $form;
}
$x = change($array, $arr[$key+5][$value-1] = $key-$value);
$y = change($array, $arr[$key+5][$key+100] = $key+$value);

how can this be done?

Joe Doe
  • 523
  • 2
  • 9

1 Answers1

1

Somebody will bash all of the evils of eval but if it is not user supplied (un-trusted) data, then this works:

function change($array, $form) {
    foreach ($array as $key => $value) {
        eval("\$result$form;");
    }
    return $result;
}

You need to call it with a string as shown:

$x = change($array, '[$key+5][$value-1] = $key-$value');
$y = change($array, '[$key+5][$key+100] = $key+$value');

This builds a string that looks like this: $result[$key+5][$key+100] = $key+$value; and evaluates it as PHP code.

It would be a lot more work, but you could pass in something to parse and adapt it to How to access and manipulate multi-dimensional array by key names / path?.

AbraCadaver
  • 78,200
  • 7
  • 66
  • 87
  • everytime i read about `eval` i understood why its dangerous but never cared about it because i never thought or knew how to use it in any of my codes - now i know – Joe Doe Jul 18 '19 at 20:38
  • is there other methods to mimic this without `eval` too? – Joe Doe Jul 18 '19 at 20:54