2

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

2 Answers 2

8

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")));
Sign up to request clarification or add additional context in comments.

Comments

3

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.

Comments

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.