1

I have a foreach loop that will echo out all the selection made by the user from the checkboxes.

I am trying to store the value into a variable called $getCentralArea. However, when I echo $getCentralArea it shows 4 - only the last value of the selected checked box. The correct value that I should get is 1,2,3,4.

if(!empty($_POST['centralArea'])) 
{
    foreach($_POST['centralArea'] as $centralArea) 
    {
        $getCentralValue = $centralArea.","; //Output will be in the following format 1,2,3,4
    }
}else{ $getCentralArea="";}
2
  • use this $getCentralValue .= $centralArea.","; for string or create array. Commented Sep 29, 2015 at 4:47
  • use $getCentralValue[] to make the array of all elements. Commented Sep 29, 2015 at 4:48

4 Answers 4

1

You could concatenate but that leaves a trailing comma. Also, no need to loop, just implode() the array:

$getCentralValue = implode(',', $_POST['centralArea']);
Sign up to request clarification or add additional context in comments.

Comments

0

You need to concatenate your $centralAreas to $getCentralValue using the . (or .=) operator, else, it just overwrites $getCentralValue every time you loop:

if(!empty($_POST['centralArea'])) 
{
    foreach($_POST['centralArea'] as $centralArea) 
    {
        $getCentralValue .= $centralArea.","; //Output will be in the following format 1,2,3,4
    }
    $getCentralValue = rtrim($getCentralValue, ",");
} else{ $getCentralArea=""; }

Comments

0

try like this: Use implode.

either

$result=implode(",",$_POST['centralArea']);//Output will be in the following format 1,2,3,4

or this in case you do not want post variables to use directly.

      $getCentralValue=array();
        foreach($_POST['centralArea'] as $centralArea) 
        {
            $getCentralValue[]= $centralArea; 
        }

        $result=implode(",",$getCentralValue);//Output will be in the following format 1,2,3,4

    echo $result;

Comments

0

I would rather push them in array and later print them using implode

if(!empty($_POST['centralArea'])) 
            {
              $stack = array();
                foreach($_POST['centralArea'] as $centralArea) 
                {
                    array_push($stack,$centralArea);
               }
//print in 1,2,3,4
$comma_separated = implode(",", $stack);

echo $comma_separated;

            }

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.