Return array from foreach() loop and print_r() it
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>";
?>
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.
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>";
$_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
)
精彩评论