1

I have a piece of code like

$id = $_POST['id'];
$name = $_POST['name'];
$story = $_POST['story'];
$imgurl = $_POST['imgurl'];
$thisAction = $_POST['thisAction'];

As you can see, the variable names I'm using are equal to the keys of the $_POST array. Is it possible to accomplish the above with a loop?

6
  • 1
    it's called "variable variables", and please don't go there. what's wrong with using $_POST['id']? Commented Aug 20, 2015 at 16:51
  • @MarcB I don't want to have to use $_POST['id'] multiple times because that would be inefficient. Better to save a copy of the value returned by it. Commented Aug 20, 2015 at 17:13
  • and other than saving a few characters while tyipng, how would it be more efficient to have to replicate $id everywhere? Commented Aug 20, 2015 at 17:14
  • Assign it once to a variable $id = isset($_POST['id']) ? $_POST['id'] : 0; and be done with it. Not sure how that would be more efficient, though. edit: slow again... Commented Aug 20, 2015 at 17:14
  • 1
    you're waaaaaaay overoptimizing. the few microseconds you're going to save could be better spent optimizing real problems, Commented Aug 20, 2015 at 17:29

1 Answer 1

2

Yes, it's possible using variable variables:

foreach($_POST as $key => $value) {
    $$key = $value;
}

or using extract:

extract($_POST);

But please be aware that doing this will introduce a potential security hole.

It's in fact like simulating PHP's register_globals directive, which introduces lots of security issues.


You could assign a subset of $_POST variables, this is a much safer way:

$keys = array('id', 'name', 'story', 'imgurl', 'thisAction');
foreach($keys as $key) {
    $$key = $_POST[$key];
}

or using extract:

$whitelisted = array_intersect_key($_POST, array('id', 'name', 'story', 'imgurl', 'thisAction')); 
extract($whitelisted);
Sign up to request clarification or add additional context in comments.

1 Comment

Alternative/Additional addition could be to pass EXTR_SKIP to extract.

Your Answer

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