Question

How can i array a string, in the format that $_POST does... kind of, well i have this kind of format coming in:

101=1&2020=2&303=3

(Incase your wondering, its the result of jQuery Sortable Serialize... I want to run an SQL statement to update a field with the RIGHT side of the = sign, where its the left side of the equal sign? I know the SQL for this, but i wanted to put it in a format that i could use the foreach($VAR as $key=>$value) and build an sql statement from that.. as i dont know how many 101=1 there will be?

I just want to explode this in a way that $key = 101 and $value = 1

Sounds confusing ;) Thanks so so much in advanced!!

Was it helpful?

Solution

$input = "101=1&2020=2&303=3";
$output = array();
$exp = explode('&',$input);
foreach($exp as $e){
   $pair = explode("=",$e);
   $output[$pair[0]] = $pair[1];
}

OTHER TIPS

See the parse_str function.

It's not the most intuitive function name in PHP but the function you're looking for is parse_str(). You can use it like this:

$myArray = array();
parse_str('101=1&2020=2&303=3', $myArray);
print_r($myArray);

One quick and dirty solution:

<?php
$str = "101=1&2020=2&303=3";
$VAR = array();
foreach(explode('&', $str) AS $pair)
{
    list($key, $value) = each(explode('=', $pair));
    $VAR[$key] = $value;
}
?>
parse_str($query_string, $array_to_hold_values);

Explode on the & to get an array that contains [ 101=1 , 2020=2 , 303=3 ] then for each element, split on the = and push the key/value pair onto a new array.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top