2

I am doing some study on arrays, and I am trying to resolve how to store the values of a foreach loop into an array which I can then print_r().

My script works fine with the exception of the $array = foreach()... And as you can see I called return; to return the results to the $array variable, but I am getting a parse error.

Here is my code so far:

<?php

<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
  <input type="radio" name="DataNameOne" value="Value 1">
  <input type="radio" name="DataNameTwo" value="Value 2">
  <input type="radio" name="DataNameThree" value="Value 3">
  <input type="submit" />
</form>
<?php

$array = foreach ($_POST as $key=>$value) {
    if (stristr($key, "section")) {
        $section = $value;
        $section_name = $key;
        return;
    }
    echo "Key is: $key and Valus is: $value";
}

echo "<pre>";
print_r($array);
echo "</pre>";

?>
0

3 Answers 3

7

You could just do

$array = $_POST;

since $_POST is already an array. However if you want to use the foreach loop to iterate a source array and copy only certain parts of it, you'd do something like:

$new_array = array()
foreach($original_array as $key => $value) {
    if (...filter condition(s)...) {
        $new_array[$key] = $value;
    }
}

There's also array_map(), preg_grep(), etc... which you mangle/filter array as you please.

Sign up to request clarification or add additional context in comments.

1 Comment

I way over complicated this one! I think the first thing I learned was $_POST was an array. Thanks for the tip and info resolved.
0

I am really sorry this post was so confusing. My code was copied from a source and I've been changing the names and values around in the html and php to learn this..

I was over complicating the entire thing, and resolved it by:

foreach ($_POST as $key=>$value) {
    if (stristr($key, "section")) {
        $section = $value;
        $section_name = $key;
            return;
    }
    echo "Key is: $key and Valus is: $value";
}


echo "<pre>";
print_r($_POST);
echo "</pre>";

Comments

0
$_POST is array.if we use print_r($_POST); of above form, we find array:-
code:-
-------------

$data=array(); 
$new_array=array(); 
echo"<pre>";
print_r($_POST);
$data[]=$_POST['DataNameOne'];
$data[]=$_POST['DataNameTwo'];
$data[]=$_POST['DataNameThree'];
print_r($data);   
foreach($ as $key => $value) { 
          if (...filter condition(s)...) {  
           $new_array[$key]=$value;
         } }

output:-
-------------
Array
(
    [DataNameOne] => Value 1
    [DataNameTwo] => Value 2
    [DataNameThree] => Value 3
)

Array
(
    [0] => Value 1
    [1] => Value 2
    [2] => Value 3
)

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.