I have a form that gives me multiple arrays when submit. My question is if there is a smart way to echo out (to show the user) all the arrays instead of doing a foreach for each array?
Could a solution be to do a function with a foreach loop?
HTML from the TASKS input:
<td><input type="checkbox" name="tasks[<?php echo($value[0]);?>]"value=<?php echo($key[0]);?>></td>
My PHP script:
if(isset($_POST['submit'])) {
$tasks = $_POST['tasks'];
$user = $_POST['user'];
$pickup_at = $_POST['pickup_at'];
$message = $_POST['message'];
$price = $_POST['price'];
$part_missing = $_POST['part_missing'];
Foreach ex. on the TASKS array
foreach($tasks as $key => $keys)
{
echo $key ."<br>";
}
All the arrays should have indexes in parallel. You only need to use the indexes from one of them, and can then use that as indexes into all the rest:
foreach ($tasks as $i => $task) {
echo "Task $i: $task<br>";
echo " User: {$user[$i]}<br>";
echo " Pickup at: {$pickup_at[$i]}<br>";
...
}
foreach($tasks as $key => $keys)
{
echo $key ."<br>";
}
If its just use to add BR in keys another ways is
// will give you same output that foreach() gives you.
echo implode("<br>", array_keys($tasks));
Instead of
foreach($tasks as $key => $keys) {
echo $key ."<br>";
}
you can do:
echo(implode('<br>', $tasks));
This puts <br> between the elements of $task and produces a string. Depending on the HTML context where you echo the string you may need or may need not to append an extra <br> after the last element.
I think there is problem with your form. Your html sholud be this:
<td><input type="checkbox" name="tasks[]" value="<?php echo($value[0]);?>"></td>
Insted of this:
<td><input type="checkbox" name="tasks[<?php echo($value[0]);?>]"value=<?php echo($key[0]);?>></td>
After that you can print the values like this:
echo implode(',',$tasks);
echo "<pre>"; print_r($tasks); echo "</pre>";
You will need to do some kind of iteration - foreach being the most obvious. You can also use other native functions like array_walk:
array_walk($array, function($val, $key) {
echo $key, PHP_EOL;
});
But it does't really add anything here. I'd stick with foreach or var_dump.
Related
So I would like to create just one loop to parse the json data i have. I can successfully parse it in 2 foreach loops however when trying to combine in one loop using $key => $value the $key returns nothing when called. How can I successfully take the 2 foreach loops I have here and combine them into one?
$contents = file_get_contents($url);
$results = json_decode($contents, true);
$jsonList = $results['genres'];
foreach($jsonList as $key) {
$GenreID = $key['id'].'<br>';
echo $GenreID;
}
foreach($jsonList as $key => $value) {
$GenreName = $value['name'].'<br><br>';
echo $GenreName;
}
The json data is as follows:
{"genres":[{"id":28,"name":"Action"},{"id":12,"name":"Adventure"},{"id":16,"name":"Animation"},{"id":35,"name":"Comedy"},{"id":80,"name":"Crime"},{"id":99,"name":"Documentary"},{"id":18,"name":"Drama"},{"id":10751,"name":"Family"},{"id":14,"name":"Fantasy"},{"id":36,"name":"History"},{"id":27,"name":"Horror"},{"id":10402,"name":"Music"},{"id":9648,"name":"Mystery"},{"id":10749,"name":"Romance"},{"id":878,"name":"Science Fiction"},{"id":10770,"name":"TV Movie"},{"id":53,"name":"Thriller"},{"id":10752,"name":"War"},{"id":37,"name":"Western"}]}
You can still use $key as an index when also extracting the $value.
However note that you shouldn't be assigning the line breaks to your variables, and should instead consider them part of the view by echoing them out independently:
$contents = file_get_contents($url);
$results = json_decode($contents, true);
$jsonList = $results['genres'];
foreach($jsonList as $key => $value) {
$GenreID = $key['id']; // Depending on structure, you may need $value['id'];
$GenreName = $value['name'];
echo $GenreID . '<br>';
echo $GenreName . '<br><br>';
}
Your single loop below here.
foreach($jsonList as $key)
{
$GenreID = $key['id'].'<br>';
echo $GenreID;
$GenreName = $value['name'].'<br><br>';
echo $GenreName;
}
$key is a assosative array.Therefore it had some index.So you can use this index in single loop.
It seems you get confused over your data structure. Seeing the json, the resulting "$jsonlist" supposed to contain array with id and value as keys.
You can iterate over it and extract the the appropriate key.
Myabe something like this:
foreach($jsonlist as $value) {
echo "id: " . $value['id'] . "\n";
echo "name: " . $value['name'] . "\n";
}
extra bonus, if you want to create 1 level array from your json based on id with the name you could try array reduce using anon function like this:
$jsonlist = array_reduce($jsonlist, function($result, $item){
$result[$item['id']] = $item['name'];
return $result;
}, []);
extra neat for transformation of static structure data.
I want to change the value of the $key because I have array_splice inside the loop which change the position of my values so - it mess up the value I need in a specific place.
I tried $key-- but it doesn't work.
for example when I print the $key after I do echo $key it's fine but when I echo $key just after the foreach loop I get the worng value.
Any ideas?
foreach ($cut as $key => $value) {
echo "foreach key:".$key."<br>";
if(in_array($value,$operators))
{
if($value == '||')
{
echo "found || in position:".$key."<br>";
if(($key+1<sizeof($cut)))
{
$multi = new multi;
echo "<br>"."key-1: ";
print_r($cut[$key-1]);
echo"<br>";
echo "<br>"."key+1: ";
print_r($cut[$key+1]);
echo"<br>";
$res = $multi->orex($cut[$key-1],$cut[$key+1],$numString);
$cut[$key-1]= $res;
array_splice($cut,$key,1);
array_splice($cut,$key,1);
$key--; //here trying to change the key
echo "new string:";
print_r($cut);
echo "<br>";
echo "key:".$key."<br>";
}
}
}
}
Updated
I don't think it is a good idea to change the array itself inside the foreach loop. So please crete another array and fill data into it, which will be your result array. This method works well when your array data is not big, in other words, most situations.
Origin
I don't know what do you mean. Let me give it a guess...
You want:
foreach($arr as $key=>$val){
$newkey = /* what new key do you want? */
$arr[$newkey] = $arr[$key];
unset($arr[$key]);
}
I can usually do pretty decent with basic arrays, but this one has put my head vs the wall.
I am trying to pass some information (for a menu) through a function, and return it in a formatted fashion.
My desired end result is to send some information like this. I need to be able to repeat the array until it is empty in the event that I have a number of fields
$Sort = array('imgup.jpg','imagedn.jpg','Name','imgx.jpg','imagy.jpg','Name4');
NewSortBox($Sort);
and have an end result that would return like
<div>Name <img src='imgup.jpg'><img src='imgdn.jpg'></div>
<div>Name4 <img src='imgx.jpg'><img src='imgy.jpg'></div>
I have figured out that I have to use the Array_Chunk function to break the array, but I am not able to figure out how to make it properly use the foreach or loop functions.
function NewSortBox(&$array){
$newArray = array_chunk($array, 3, false);
$i = 0;
foreach ($newArray as $inner_array) {
$i++;
echo "<div>";
while (list($key, $value) = each($inner_array)) {
echo "$key: $value";
// Here is where I am totally lost, I want to acheive something like ??
// echo "$value[1] <img src='$value[2]'><img src='$value[3]'>";
}
echo "</div>";
}
Something like this may help to get the desired result:
$newArray = array_chunk($Sort, 3, false);
foreach ($newArray as $inner_array) {
echo "<div>";
list($a, $b, $c) = $inner_array;
echo $c.":".$b.":".$a; //arrange the variables as required
echo "</div>";
}
I have two array output (using preg_match_all), for example: $name[1] and $family[1].
i need to put these arrays together, and i use foreach as this:
foreach( $name[1] as $name) {
foreach( $family[1] as $family) {
echo $name.$family.'<br />';
}
}
but it don't work.
(each foreach loop works separately)
Assuming they have matching keys for the loop:
foreach( $name as $key => $value) {
echo $value[$key] . $family[$key] . '<br />';
}
This will go through each match for $name and print it out, and then print out the corresponding $family with it. I don't think you want to hardcode [1].
If you do, I'm a little confused and would like to see a var_dump of both $name and $family for clarification.
$together= array();
foreach( $name as $key => $n) {
$tuple= array('name'=>$name[$key],'family'=>$family[$key]);
$together[$key]= $tuple;
}
foreach( $together as $key => $tuple) {
echo "{$tuple['name']} {$tuple['family']}<br />";
}
Use array_combine():
Creates an array by using the values from the keys array as keys and
the values from the values array as the corresponding values.
PHP CODE:
$nameFamilly=array_combine($name[1] , $family[1]);
foreach( $nameFamilly as $name=>$familly) {
echo $name.$family.'<br />';
}
HTML example:
<form method="post" id="form" action="form_action.php">
<input name="email" type="text" />
</form>
User fills input field with: dfg#dfg.com
echo $_POST['email']; //output: dfg#dfg.com
The name and value of each input within the form is send to the server.
Is there a way to get the name property?
So something like..
echo $_POST['email'].name; //output: email
EDIT:
To clarify some confusion about my question;
The idea was to validate each input dynamically using a switch. I use a separate validation class to keep everything clean. This is a short example of my end result:
//Main php page
if (is_validForm()) {
//All input is valid, do something..
}
//Separate validation class
function is_validForm () {
foreach ($_POST as $name => $value) {
if (!is_validInput($name, $value)) return false;
}
return true;
}
function is_validInput($name, $value) {
if (!$this->is_input($value)) return false;
switch($name) {
case email: return $this->is_email($value);
break;
case password: return $this->is_password($value);
break;
//and all other inputs
}
}
Thanks to raina77ow and everyone else!
You can process $_POST in foreach loop to get both names and their values, like this:
foreach ($_POST as $name => $value) {
echo $name; // email, for example
echo $value; // the same as echo $_POST['email'], in this case
}
But you're not able to fetch the name of property from $_POST['email'] value - it's a simple string, and it does not store its "origin".
foreach($_POST as $key => $value)
{
echo 'Key is: '.$key;
echo 'Value is: '.$value;
}
If you wanted to do it dynamically though, you could do it like this:
foreach ($_POST as $key => $value)
{
echo 'Name: ', $key, "\nValue: ", $value, "\n";
}
Loop your object/array with foreach:
foreach($_POST as $key => $items) {
echo $key . "<br />";
}
Or you can use var_dump or print_r to debug large variables like arrays or objects:
echo '<pre>' . print_r($_POST, true) . '</pre>';
Or
echo '<pre>';
var_dump($_POST);
echo '</pre>';
Actually I found something that might work for you, have a look at this-
http://php.net/manual/en/function.key.php
This page says that the code below,
<?php
$array = array(
'fruit1' => 'apple',
'fruit2' => 'orange',
'fruit3' => 'grape',
'fruit4' => 'apple',
'fruit5' => 'apple');
// this cycle echoes all associative array
// key where value equals "apple"
while ($fruit_name = current($array)) {
if ($fruit_name == 'apple') {
echo key($array).'<br />';
}
next($array);
}
?>
would give you the output,
fruit1
fruit4
fruit5
As simple as that.
current(array_keys($_POST))
should give you what you are looking for. Haven't tested though.
Nice neat way to see the form names that are, or will be submitted
<?php
$i=1;
foreach ($_POST as $name => $value) {
echo "</b><p>".$i." ".$name;
echo " = <b>".$value;
$i++;
}
?>
Just send your form to this script and it will show you what is being submitted.
You can use a foreach Loop to get all values that are set.
foreach ($_POST AS $k=>$v){
echo "$k is $v";
}
Your example
echo $_POST['email'].name; //output: email
wouldnt make sense, since you already know the name of the value you are accessing?