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?
Related
I have the following function in my php program.
$out = "";
printArray($_POST);
function printArray($array){
global $out;
foreach ($array as $key => $value){
$out = "$key: $value <br>";
}
}
echo $out;
Its supposed to get all my post values along with there variable names and save it all to a variable but it only echos out the last one in my list. Meanwhile if i dont save the output of the foreach to a variable...
printArray($_POST);
function printArray($array){
foreach ($array as $key => $value){
echo "$key: $value <br>";
}
}
it outputs just fine.
first_name: Test
last_name: Test
dob1:
dob2:
dob3:
current_grade:
shcool:
M_C:
type_of_session_text:
date_session_info:
(shortened for brevity)
whats going on here?
This is because every itteration you set $out again without keeping the previous values. You could do:
function printArray($array){
foreach ($array as $key => $value){
$out .= $key.": ".$value."<br>";
}
return $out;
}
With the .= you "add" more string to that variable. The technical term is 'concatenate'.
Also, global should be avoided as it is a mayor red flag of bad programming. A function should return a value, the logic that calls the function decides what to do with it. I recommend you do a little research into 'pure' functions (easy concept).
foreach(get_field('color') as $singleColorCP2) {
$new_fields = get_fields($singleColorCP2->ID);
foreach($new_fields as $name => $value)
echo $value;
}
this is my code and it is running it prints like,
firstfield_valueasecondfield_valuea<br>
firstfield_valuebsecondfield_valueb<br>
firstfield_valuecsecondfield_valuec<br>
I'm getting crazy how to print just:
firstfield_valuea
firstfield_valueb
firstfield_valuec
I'm interested only in one column.
("name" prints the correct name of the field, but still with the same problem, in couple with the second field, I can't divide)
foreach(get_field('color') as $singleColorCP2) {
$new_fields = get_fields($singleColorCP2->ID);
foreach($new_fields as $name => $value)
if($name == 'field_name'){
$val[] = $value;
}
}
echo $val[0];
echo $val[1];
echo $val[2];
I have found this solution in the end...with if. That's not what I would have liked but it works at least and it hasnt much code.
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 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.
I am in need of a PHP-program which will take all values from a HTML-link (with GET), regardless of how much one changes things in the address-bar, and then prints it out on the page. The code I have now is this:
HTML:
Link
PHP:
<?php
Echo "Value1: "; Echo $_GET["a"]; Echo "\n";
Echo "Value2: "; Echo $_GET["b"]; Echo "\n";
Echo "Value3: "; Echo $_GET ["c"];
?>
It works as intended for just these values, but it cannot cope with, for example, another variable being added in the address bar. I need some kind of PHP-function which can look for all kinds of variables through the GET-function.
Any help is appreciated!
Use a loop (modify as needed):
foreach ($_GET as $num => $value)
{
echo 'Value ' . $num . ': ' . htmlentities($value). "<br>" . PHP_EOL;
}
References:
Control structures
htmlentities()
Something like this:
<?php
foreach ($_GET as $key => $value) {
echo htmlspecialchars($key) . " - " . htmlspecialchars($value) . "<br>";
}
?>
<?php
print_r($_GET);
?>
Use a foreach loop
foreach ($_GET as $key => $val){
echo htmlentities($key).": ".htmlentities($val)."<br />\n";
}
or simply -
echo "<pre>".print_r($_GET,1)."</pre>";
To get all values and their corresponding names:
foreach($_GET as $key => $value)
{
echo $key . ' - ' . $value;
}
$my_get = array(); // store $_GET vars
if ('GET' == $_SERVER['REQUEST_METHOD']) // check that request method is "get"
foreach ($_GET as $key => $val)
{
$my_get[$key] = $val; // store
}
output $my_get:
array (
'a' => 'value1',
'b' => 'value2',
'c' => 'value3',
)
Since $_GET is nothing but an array, you can use for each loop to get the elements of it.
you get all $_GET values using print_r($GET) ...
otherwise you could to something like this
foreach(array_keys($_GET) as $key) {
echo htmlspecialchars($_GET[$key]);
}
Later Edit : took into account the security issue exposed in the comment
using this method is good because you know what kind of variable you have then you could do something cool like :
if ($key == 'a') do this
if ($key == 'b' && $_GET[$key] == 'bar') do that