Joe
Joe

Reputation: 1635

Add previous value in foreach - PHP

Let's say I have data string like this...

one=1&two=2&three=3&four=4&two=2

I'm using php foreach to grab the key/value and sort how I need it at this point

foreach($_POST as $key => $value) {
   if ($key == "two") {
    // $result = Take $value and add it to the previous $value .",";
   }
}

The goal I am trying to reach is how do I take the duplicate keys and add the previous value generated in the loop. For example: The solution would be $result = 2,2,

Upvotes: 1

Views: 325

Answers (5)

Gareth
Gareth

Reputation: 5719

Bearing in mind Rocket's advice about multiple POSTed values, you could use implode() on any arrays that arrive:

foreach($_POST as $key=>$value)
{
    if(is_array($value))
        $_POST[$key]=implode(',',$value);
}

to get the string value that you seem to be after.

Upvotes: 1

ContextSwitch
ContextSwitch

Reputation: 2837

//initial data string
$string = "one=1&two=2&three=3&four=4&two=2";

$results = array();

$data = explode('&', $string);

foreach($data as $param) {

    $query = explode('=', $param);

    $key = $query[0];
    $value = $query[1];

    // check to see if the key has been seen before. 
    // if not, store it in an array for now.
    if(!isset($results[$key])){
        $results[$key] = array($value);
    }
    else{
        // the key is a duplicate, store it in the array
        $results[$key][] = $value;
    }

}

// implode the arrays so that they're in the $result = "2,2" format
foreach($data as $key => $value){
    $data[$key] = implode(',', $value);
}

Also its been mentioned, but if this is coming from a server post then you won't get duplicate keys.

Upvotes: 1

Pethical
Pethical

Reputation: 1482

This will not work. You get only the last value from POST, GET and REQUEST. You need to parse the $_SERVER['QUERY_STRING'], and if you parsed it, you can iterate your array:

foreach(explode('&',$_SERVER['QUERY_STRING']) as $k => $v)
{
 $val = explode('=',$v);
 $result[$val[0]] = isset($result[$val[0]]) ? $result[$val[0]].','.$val[1]:$val[1];
}

Upvotes: 1

gen_Eric
gen_Eric

Reputation: 227240

If you're POSTing the string in the question to your server, you would only see one value of two, not both. The 2nd one would overwrite the first value.

If you want multiple values for a key, you can make it an array by using [].

one=1&two[]=2&three=3&four=4&two[]=2

Now, $_POST['two'] will be an array (one, three and four will be strings).

Upvotes: 1

rastafarianmenagerie
rastafarianmenagerie

Reputation: 90

Store them as an array outside the foreach loop.

$keys = [];
foreach($_POST as $key => $value) {
   if ($key == "two") {
     $keys[] = $value;
   }
}
return $keys

Upvotes: 0

Related Questions