Getting both or one Checkbox value in for each loop - php

I have a form that the user can submit either 1 or 2 checked boxes. It must be at least 1. The checkbox setup looks like so:
<input name="request['+fields+'][Type of Folder:]"
id="cbpathCDB'+fields+'" type="checkbox"
value="Content Database" class="cbShowPath required" data-id="'+fields+'"/>
<input name="request['+fields+'][Type of Folder:]"
id="cbpathEFS'+fields+'" type="checkbox"
value="File System" class="efsShowPath required" data-id="'+fields+'"/>
There is other inputs that are also being submitted, so I am using this for each:
$a=$_REQUEST['request'];
foreach ($a as $name) {
foreach ($name as $key => $desc) {
if ($desc !== '') {
$note.= $key;
$note.= $desc;
}
}
}
This gets all the data fine if the user checks ONE checkbox, but if the user checks both checkboxes, only the value of the FIRST checkbox is shown.
What do I need to do here in order to get both values?
Do I need a 3rd foreach in here to get name="request[][][]"?
EDIT: some updates here...
If I use his foreach:
foreach ($a as $name) {
foreach ($name as $key => $desc) {
foreach ($desc as $d){
$note.= $key;
$note.= $d;
}
if ($desc !== '') {
$note.= $key;
$note.= $desc;
}
}
}
I get these results echoed out:
Type of Folder:Content DBType of Folder:File SystemType of Folder:Array
If I use his foreach:
foreach ($a as $name) {
foreach ($name as $key => $desc) {
if ($desc !== '') {
$note.= $key;
$note.= $desc;
}
}
}
I get these results echoed out:
Type of Folder:Array

Change the name of the form elements to
request['+fields+'][Type of Folder:][]
So for your code
<input name="request['+fields+'][Type of Folder:][]" id="cbpathCDB'+fields+'" type="checkbox" value="Content Database" class="cbShowPath required" data-id="'+fields+'"/>
<input name="request['+fields+'][Type of Folder:][]" id="cbpathEFS'+fields+'" type="checkbox" value="File System" class="efsShowPath required" data-id="'+fields+'"/>
This will make $_REQUEST['request']["'+fields+'"]['Type of Folder:'] an array containing the value of each checked box.
You need to modify the part of your code working with $desc to include another loop.
foreach ($a as $name) {         
foreach ($name as $key => $desc) {
switch (gettype($desc)) {
case 'array':
foreach ($desc as $i => $item) {
$note .= "{$key}[{$i}]";
$note .= $item;
}
break;
case 'string':
default:
if ($desc !== '') {
$note.= $key;
$note.= $desc;
}
}
}
}

Related

Foreach - How to print a only the third and 4th value

I have form with the option to add more fields.
I'd like to know if i could print the individual values of a foreach loop.
eg. if the person added to forms and i want to print the second value how would i do that ?
So Far what i have tried only printed the first Character.
HTML
<form action="careerHistoryCon.php" method="post" enctype="multipart/form-data">
<label for="industry[]">Industry Segmentation</label>
<input type="text" name="industry[]" id="" placeholder="Finance / Insurance ...."><br>
<p>To add another feild Click here </p> <br><br>
</form>
JQ
$("#addMore").click(function(){
$(".form-group:last").clone().appendTo(".wrapper");
});
PHP - Problem here
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (isset($_POST['submit'])){
$industry= $_POST['industry'];
foreach ($industry as $key => $value) {
echo $value[0]. '<BR>';
echo $value[1]. '<BR>';
}
}
You are pretty near to the solution. Using foreach on an array gives you the index as key.
foreach ($industry as $key => $value) {
if($key == 1) echo $value; // array starts with 0, so 1 is the second element.
}
or you can use an iterator
// using foreach
$i = 0;
foreach ($industry as $key => $value) {
if($i == 1) echo $value;
$i++;
}
//using for
for($i = 0; $i < count($industry); $i++) {
if($i == 1) echo $industry[$i];
}
btw. since $value is the input string of the user, $value[0] would just be the first letter the user entered. Because a string is just an array of chars.

Change foreach $key variable inside the foreach loop

Looking for a way to change $$key to something like $$key_errorso the variable will look something like: $name_error outside the foreach loop.
Here is what I have so far:
foreach ($_POST as $key => $value) {
$$key = strip_tags(mysqli_real_escape_string($mysqli, $value));
if (empty($value)) {
// change variable below to something like $$key_error ($$name_error)
$$key = 'is-invalid';
} else {
$$key = "value='$value'";
}
}
When an input is empty the user will return to the registration form, the input that is empty will have red bootstrap borders. When a field is not empty, the value will still be there so they do not have to do it all over.
<input type="text" name="name" class="form-control form-control-lg <?=$name?>" style="text-align:center;" placeholder="Voor- en achternaam" <?=$name?>>
I hope it all makes sense :)
Use arrays.
$errors = [];
$values = [];
foreach ($_POST as $key => $value) {
// validation check for $value
if (/*validation check fails*/) {
$errors[$key] = 'error message specific to this field';
} else {
$values[$key] = htmlspecialchars($value);
}
}
Then in your form, check for the array key matching your control name.
<input type="text" name="example"
class="<?= isset($errors['example']) ? 'is-invalid' : '' ?> other classes"
value="<?= $values['example'] ?? '' ?>">
You can also output the specific error message if you want to.
<div class="error"><?= $errors['example'] ?? '' ?></div>

Two different large array

I have problem with two arrays:
$pole1 = array(
array("klic"=>"banan", "jmeno"=>"Banán"),
array("klic"=>"pomeranc", "jmeno"=>"Pomeranč"),
);
$pole2 = array(
array("klic"=>"banan"),
);
Now I need foreach data:
foreach ($pole1 as $key => $val){
//all data from $pole
echo $val
//and here if "klic" from $pole1 == "klic" from $pole2
if ($pole2[$key]["klic"] == $pole1["klic"])
echo "YES"; // - **not working**
}
I need to check if data from $pole1 equals data from $pole2 and write some text but I need to write all data from $pole1.
You meant that?
foreach ($pole1 as $key => $val) {
if ( isset($pole2[$key]["klic"] &&
($pole2[$key]["klic"] == $pole1[$key]["klic"]) )
echo "YES";
}
try this
foreach($pole1 as $k1 => $arrays) {
foreach($arrays as $k2 => $val) {
if($pole2[$k1][$k2] == $val) {
// $pole1[$k1][$k2] is equal to $pole2[$k1][$k2]
}
}
This will echo every entry in pole1 and check every entry in pole1 with every entry in pole2.
foreach($pole1 as $val){
echo($val);
foreach($pole2 as $val2){
if($val['klic']==$val2['klic']) echo 'YES';
}
}

Adding a value to a PHP associative array

I'm passing an array inside a GET(url) call like this:
&item[][element]=value
Then I do my stuff in PHP:
$item = $_GET['item'];
foreach ($item as $aValue) {
foreach ($aValue as $key => $value) {
echo '$key $value';
The problem I'm facing is that I need to have(echo) a third 'value':
echo '$key $value $thirdValue';
Do I have to change my the URL I'm passing or the foreach? And how do I do that? I Googled but I can't make heads nor tails out of it.
$item = $_GET['item'];
$item_temp=array_values($item);
foreach ($item as $aValue) {
foreach ($aValue as $key => $value) {
echo '$key $value'.$item_temp[2];
}
}
<?php
$item = $_GET['item'];
$r=array();
foreach($item as $rt){
array_push($r,array(key($rt)=> $rt));
}
foreach($r as $rt){
foreach($rt as $rt2){
$k = key($rt2);
echo $k.'__'.$rt2[$k] ;
echo "<br>";
}
}
?>
it's Work .

How to get index's value from $_POST using foreach

I want to know the correct code to detect only numerical $_POST fields coming from the form.
Please correct my code.
foreach ($_POST as $vals) {
if (is_numeric($vals)) {
if (is_numeric($vals[$i]) && ($vals[$i]!="0")) {
//do something
}
}
$_POST = array_filter($_POST, "is_numeric");
The above will remove all non-numeric array items.
foreach (array_filter($_POST, "is_numeric") as $key => $val)
{
// do something
echo "$key is equal to $val which is numeric.";
}
Update:
If you only want those like $_POST[1], $_POST[2], etc..
foreach ($_POST as $key => $vals){
if (is_numeric($key)){
//do something
}
}
try:
foreach ($_POST as $key => $vals){
//this is read: $_POST[$key]=$value
if (is_numeric($vals) && ($vals!="0")){
//do something
}
}
if(isset($_POST)){
foreach($_POST as $key => $value){
if(is_numeric($key)){
echo $value;
}
}
}
Compare the keys
Try this:
foreach ($_POST as $key => $val)
{
if (is_numeric($key))
{
// do something
}
}
The following code with isset() trying to work on an array is invalid.
if(isset($_POST)){ //isset() only works on variables and array elements.
foreach($_POST as $key => $value){
if(is_numeric($key)){
echo $value;
}
}
foreach ($_POST as $key => $val)
{
if (is_numeric($key))
{
// do something
}
}
Better, but now foreach will make a copy of $_POST and put in in memory for the duration of the loop (Programming PHP: Ch. 6, p. 128-129). I hope buffer overflows or out of memory errors don't jump up and bite you. :-)
Perhaps it would be wiser to determine some facts about $_POST with is_array(), empty(), count() and others before getting started, such as ...
if(is_array($_POST) && !empty($_POST))
{
if(count($_POST) === count($arrayOfExpectedControlNames))
{
//Where the the values for the $postKeys have already been validated some...
if(in_array($arrayOfExpectedControlNames, $postKeys))
{
foreach ($_POST as $key => $val) //If you insist on using foreach.
{
if (is_numeric($key))
{
// do something
}
else
{
//Alright, already. Enough!
}
}
}
else
{
//Someone is pulling your leg!
}
}
else
{
//Definitely a sham!
}
}
else
{
//It's a sham!
}
Still, the $val values need some validation, but I'm sure you are up on that.

Categories