Re: Comparing string to array

From: Date: Tue, 19 Jun 2007 09:16:02 +0000
Subject: Re: Comparing string to array
References: 1  Groups: php.general 
Request: Send a blank email to php-general+get-257377@lists.php.net to get a copy of this message
Richard Davey wrote:
Hi all, Ok it's 2am, my brain has gone to mush and I am having trouble figuring out an easy way to do this, can anyone shed some light? Take a peek at the following code: // START <pre> <?php
    print_r($_POST);
        $userparam = "test['sam'][]";
    //  How to check if $userparam exists in the $_POST array
    //  and get all the values from it?
        //  Obviously this won't work, but you get the idea:
    if (isset($_POST[$userparam]))
    {
        echo 'yeah';
        $values = $_POST[$userparam];
    }
    else
    {
        echo 'nah';
    }
?> </pre> <form method="post"> <input type="checkbox" name="test['bob'][]" value="red">red<br> <input type="checkbox" name="test['bob'][]" value="green">green<br> <input type="checkbox" name="test['bob'][]" value="blue">blue<br> <input type="checkbox" name="test['sam'][]" value="red2">red2<br> <input type="checkbox" name="test['sam'][]" value="green2">green2<br> <input type="checkbox" name="test['sam'][]" value="blue2">blue2<br> <input type="submit"> </form> // END From the code above I'm trying to figure out how to tell if the $userparam exists in the $_POST array. PHP automatically expands the form element name into multi-dim arrays within $_POST, so a simple 'isset' as shown in the code above won't play because it's got a totally useless array key passed to it. I need a way to turn the string: "test['sam'][]" into something I can look into $_POST for. Any ideas? The coffee boost is wearing off, but I want to get this licked tonight :-\
Do you have control over what $userparam looks like? I'm not entirely sure what you're after due to the [] on the end of it, but I'm going to assume you want to know if any of the 'sam' checkboxes were ticked. Maybe the following is a possibility... $userparam = "test.sam"; // How to check if $userparam exists in the $_POST array // and get all the values from it? $idx = '[\''.implode('\'][\']', explode('.', $userparam)).'\']'; eval('$isset = isset($_POST'.$idx.');'); // Obviously this won't work, but you get the idea: if ($isset) {
    echo 'yeah';
    eval('$values = $_POST'.$idx.';');
} else {
    echo 'nah';
} Untested, and remember that eval is pure evil. If you can't control $userparam and it has to look like you have it then you're parsing of it is a little more involved, but still fairly simple. What are you actually trying to do? Where will $userparam actually come from? There is almost certainly a better way to do this, but without knowing all the details I'd be peeing in the wind. -Stut -- http://stut.net/

« previous php.general (#257377) next »