Results 1 to 6 of 6

Thread: Assigning variables within a foreach loop?

  1. #1
    Join Date
    Sep 2008
    Location
    Bristol - UK
    Posts
    842
    Thanks
    32
    Thanked 132 Times in 131 Posts

    Default Assigning variables within a foreach loop?

    Hi there, I'm trying to assign variables dynamically through a foreach loop, where I want to assign the value of a variable in an array to its own variable, something like this:

    PHP Code:
    $fields = array("name","time","where","phone_no","job_description","quoted_price");

    foreach(
    $fields as $field)
    {
        if(empty(
    $_POST['{$field}']))
        {
            die(
    "You need to complete all fields.");
        }
        else
        {
            $ . 
    $field $field;
        }

    Obviously this doesn't work but I'm curious to know how you could achieve it.

    Like depending on the value in the array, assign that variable to itself. Of course I could get the same results in a different way but I like to make efficient code

    I hope you can see what I mean...

    Say "time" is being passed through:

    $time = $field

    Ok, well just ask me if you don't understand what I'm getting at.

    Thanks,

    Jack.

  2. #2
    Join Date
    Jun 2005
    Location
    英国
    Posts
    11,876
    Thanks
    1
    Thanked 180 Times in 172 Posts
    Blog Entries
    2

    Default

    To start with, I'd just like to say that this (like just about every usage of variable variables) is very very bad and should not be done. If you find accessing your $_POST variables too much hard work, you have several options: you can rename the array ($s =& $_POST;) and access them that way ($s['name']); you can create a function (function s($s) { return $_POST[$s; } to access them (s('name');), which is nice because it allows you to insert a mysql_real_escape_string() or the like; if you don't need to access them as strings you can even cast the whole thing to an object ($s = (object) $_POST;)and access them them that way ($s->name).

    That said, it is possible to do as you ask, and in fact there is a function to do it for you (extract()), although it doesn't provide the check (for safety reasons, make sure you pass EXTR_SKIP if the input is user-generated). Using your above code, and removing all the redundant braces, we get:

    Code:
    $fields = array('name',
                    'time',
                    'where',
                    'phone_no',
                    'job_description',
                    'quoted_price');
    
    foreach ($fields as $field)
        if (empty($_POST[$field]))
            die('You need to complete all fields.');
        else
            $$field = $field;
    Note: we've used single quotes, not double quotes (double quotes provide interpolation, so they're slower; if you're not using interpolation, don't use them); we've replaced '{$field}', which is literal since it's in single quotes (if you'd put it in double quotes it would have been interpolated and worked as you expected, but it's redundant anyway) with $field; and we've used variable variable syntax $$name, where $name must be a string containing a valid variable name (http://b.lericson.se/~toxik/php_sucks_rant.log provides a basic introduction, as well as mentioning its foibles).
    Twey | I understand English | 日本語が分かります | mi jimpe fi le jbobau | mi esperanton komprenas | je comprends français | entiendo español | tôi ít hiểu tiếng Việt | ich verstehe ein bisschen Deutsch | beware XHTML | common coding mistakes | tutorials | various stuff | argh PHP!

  3. The Following User Says Thank You to Twey For This Useful Post:

    Schmoopy (02-23-2009)

  4. #3
    Join Date
    Sep 2008
    Location
    Bristol - UK
    Posts
    842
    Thanks
    32
    Thanked 132 Times in 131 Posts

    Default

    Ok cheers for that, but still not getting what I wanted, using:

    PHP Code:
    $fields = array('name');

    foreach(
    $fields as $field)
        if(empty(
    $_POST[$field]))
        {
        die(
    'You need to complete all fields.');
        }
        else
        {
        echo $
    $field $field;
        echo 
    $name;
        } 
    I passed the value 'test' from the form on my other page to this one, and I wanted to end up with $name = 'test'. At the moment they're both echoing 'name', where did I go wrong?

  5. #4
    Join Date
    Jun 2005
    Location
    英国
    Posts
    11,876
    Thanks
    1
    Thanked 180 Times in 172 Posts
    Blog Entries
    2

    Default

    Of course you are. You meant $_POST[$field] (and then you'll get them both echoing 'test', since (a = b) === b).
    Last edited by Twey; 02-23-2009 at 10:39 PM.
    Twey | I understand English | 日本語が分かります | mi jimpe fi le jbobau | mi esperanton komprenas | je comprends français | entiendo español | tôi ít hiểu tiếng Việt | ich verstehe ein bisschen Deutsch | beware XHTML | common coding mistakes | tutorials | various stuff | argh PHP!

  6. #5
    Join Date
    Sep 2008
    Location
    Bristol - UK
    Posts
    842
    Thanks
    32
    Thanked 132 Times in 131 Posts

    Default

    Ah, yes of course

  7. #6
    Join Date
    Jun 2005
    Location
    英国
    Posts
    11,876
    Thanks
    1
    Thanked 180 Times in 172 Posts
    Blog Entries
    2

    Default

    Er, that's $field, not 'field', sorry.
    Twey | I understand English | 日本語が分かります | mi jimpe fi le jbobau | mi esperanton komprenas | je comprends français | entiendo español | tôi ít hiểu tiếng Việt | ich verstehe ein bisschen Deutsch | beware XHTML | common coding mistakes | tutorials | various stuff | argh PHP!

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •