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?

0

1 Answer 1

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?.

Sign up to request clarification or add additional context in comments.

2 Comments

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
is there other methods to mimic this without eval too?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.