views:

53

answers:

2

Hi, let's say i have the following:

$vars="name=david&age=26&sport=soccer&birth=1984";

I want to turn this into real php variables but not everything. By example, the functions that i need :

$thename=getvar($vars,"name");
$theage=getvar($vars,"age");
$newvars=cleanup($vars,"name,age"); // Output $vars="name=david&age=26"

How can i get only the variables that i need . And how i clean up the $vars from the other variables if possible?

Thanks

+3  A: 

You can do something like:

function getvar($arr,$key) {
    // explode on &.
    $temp1 = explode('&',$arr);

    // iterate over each piece.
    foreach($temp1 as $k => $v) {
        // expolde again on =.
        $temp2 = explode('=',$v);

        // if you find key on LHS of = return wats on RHS.
        if($temp2[0] == $key)
            return $temp2[1];   
    }
    // key not found..return empty string.
    return '';
}

and

function cleanup($arr,$keys) {
    // split the keys string on comma.
    $key_arr = explode(',',$keys);

    // initilize the new array.
    $newarray = array();

    // for each key..call getvar function.
    foreach($key_arr as $key) {
        $newarray[] = $key.'='.getvar($arr,$key);
    }

    // join with & and return.
    return implode('&',$newarray);
}

Here is a working example.

codaddict
Thanks a bunch, it's exactly what i'm looking for!
David
+7  A: 

I would use parse_str() and then manipulate the array.

$vars="name=david&age=26&sport=soccer&birth=1984";
parse_str($vars, $varray);

$thename = $varray["name"];
$theage = $varray["age"];
$newvars = array_intersect_key($varray, 
    array_flip(explode(",","name,age")));
Bill Karwin
That's nice too +1
David
This is a better answer
SeanJA