How to select an array within an array PHP - php

I am trying to perform some array-ception here: Array within an array. I have a string forms which pass on hidden values to the next form. One of these forms submits an array of checkbox values to another form. That form then submits all previous forms into a database. It's working great except for one problem. When passing the array of checkboxes through another form, it puts the array into another array. I want to select the nested array and store it in a local variable. The array is called interests
Array ( [0] => Array ( [0] => movies [1] => art [2] => cars [3] => business [4] => comedy [5] => technology ) )
Right now my array looks like the array above. When I add [0] to $_POST['interests'] like so:
$int = $_POST['interests'][0];
It successfully stores the second array into the variable int. Problem is that it stores it as a string and not an array. It still looks like an array when I echo it out though
Array ( [0] => movies [1] => art [2] => cars [3] => business [4] => comedy [5] => technology )
How do I store the nested array in a variable. Or how do I turn the above string into an array.
Thank you

If I understood what you mean (and it's a huge if), you might use the following:
Original page:
<form method="POST" ... >
<input type='checkbox' name='passable[interests][]' value='movies'>
<input type='checkbox' name='passable[interests][]' value='art'>
<input type='checkbox' name='passable[interests][]' value='cars'>
<input type='checkbox' name='passable[interests][]' value='business'>
<input type='checkbox' name='passable[interests][]' value='comedy'>
<input type='checkbox' name='passable[interests][]' value='technology'>
</form>
Intermediate page:
<?php
function pass_previous_data ()
{
foreach ($_POST['passable'] as $name => $block)
foreach ($block as $value)
{
echo "<input type='hidden' name='passable[$name][]' value='$value'>";
}
}
?>
<form method="POST" ... >
// by default, form fields will not be forwarded
<input type='text' name='added_data' value='whatever'>
// inject previous data as hidden fields
<?php pass_previous_data (); ?>
// add more forwardable data
<input type='checkbox' name='passable[languages][]' value='English'>
<input type='checkbox' name='passable[languages][]' value='Español'>
<input type='checkbox' name='passable[languages][]' value='Deutsch'>
<input type='checkbox' name='passable[languages][]' value='Русский'>
</form>
The final page should see the whole packet of selected values as an array.
The system allows you to forward data across multiple pages by declaring input names as passable.
It makes retrieving data pretty straightforward with minimal PHP code.
All this being said, it's a pretty inefficient way of passing data around:
you generate a whole hidden HTML input to pass each single value.
You could encode your arrays with Json or PHP serialization mechanism instead, but I suppose you have your reasons to do otherwise.
Here is a one-page working demo of the above example (a little obfuscated by PHP/HTML blending though)
<!DOCTYPE html>
<meta http-equiv='Content-Type' content='text/html; charset=utf-8'>
<?php
// recreate hidden fields to forward previous post data
function pass_previous_data ()
{
foreach ($_POST['passable'] as $name => $block)
foreach ($block as $value)
{
echo "<input type='hidden' name='passable[$name][]' value='$value'>";
}
}
if (!isset($_POST['page']))
{ // first page
?>
<body onload='document.getElementById("post").submit();'>
<form method="POST" id="post">
<input type='hidden' name='page' value='2'>
<input type='checkbox' name='passable[interests][]' value='movies' checked>
<input type='checkbox' name='passable[interests][]' value='art' checked>
<input type='checkbox' name='passable[interests][]' value='cars'>
<input type='checkbox' name='passable[interests][]' value='business'>
<input type='checkbox' name='passable[interests][]' value='comedy'>
<input type='checkbox' name='passable[interests][]' value='technology' checked>
</form>
</body>
<?php } else switch ($_POST['page']) {
case '2': // second page
?>
<body onload='document.getElementById("post").submit();'>
<form method="POST" id="post">
<input type='hidden' name='page' value='3'>
<?php pass_previous_data (); ?>
<input type='text' name='added_data' value='whatever'>
<input type='checkbox' name='passable[languages][]' value='English' checked>
<input type='checkbox' name='passable[languages][]' value='Español'>
<input type='checkbox' name='passable[languages][]' value='Deutsch' checked>
<input type='checkbox' name='passable[languages][]' value='Русский' checked>
</form>
</body>
<?php break;
case '3':
// final page
echo"<pre>";print_r ($_POST);echo"</pre>";
break;
}
?>

Related

I have Multiple radio button with same name in it of array and have same values as 1

I have multiple radio button name in array with same values as 1 for all.
I need want to get if uncheck means set as zero how can I do that. Below is my code
check image its sample image but same form like i having :
html code :
<input type="radio" name="radio_name[]" id="radi_name" value="1" checked >
<label for="radio1">Set as Default</label>
PHP code :
$a[]=$_post['radio_name'];
prinr_r($a);
Current result :
Array ( [0] => 1 )
Expected result :
Array ( [0] => 1,[1] => 0,[2] => 0,[3] => 0 )
I have checked one radio button only, rest all need to zero.
use it like.
<form method='post' id='userform' action='test2.php'> <tr>
<td>Trouble Type</td>
<td>
<input type='checkbox' name='checkboxvar[]' class="check" value='1'>1<br>
<input type='checkbox' name='checkboxvar[]' class="check" value='1'>2<br>
<input type='checkbox' name='checkboxvar[]' class="check" value='1'>3
</td> </tr> </table> <input type='button' class='buttons'> </form>
<script type="text/javascript">
$(document).ready(function(){
$('.buttons').click(function(){
var checkbox_arr = [];
$('.check').each(function(){
checkbox_arr.push(+$(this).is( ':checked' ));
});
console.log(checkbox_arr);
});
});
</script>

get submitted values with PHP DOM

I want to get the values that belong to the answers of a test.
There could be any number of questions.
A question has the HTML:
<form method='post' action='calificar.php'>
<div class='pruebaAlumno'>
<h5>Pregunta 3</h5>
<h3>¿Que factores definen la capacidad de una persona?</h3>
<input type='checkbox' name='respuestaAlumno[]'
value='Voluntad'> Voluntad <br>
<input type='checkbox' name='respuestaAlumno[]'
value='Cultura'> Cultura <br>
<input type='checkbox' name='respuestaAlumno[]'
value='Hábitos'> Hábitos <br>
<input type='checkbox' name='respuestaAlumno[]'
value='Habilidad'> Habilidad <br>
<input type='checkbox' name='respuestaAlumno[]'
value='Perfil'> Perfil <br>
<input type='checkbox' name='respuestaAlumno[]'
value='Dones'> Dones <br>
<input type='hidden' name='idPregunta' value='41'>
<input type='hidden' name='tipo' value='C'>
</fieldset>
</div> <div class='calificar'>
<input type='submit' name='calificar' value='enviar' >
</div>
</form>
I want to get
Answer (respuestaAlumno)
questionID (idPregunta)
type (tipo)
from each question.
Then I want to save the data in an array.
A test can have as many questions as the teacher wants. The form has one submit button.
I´ve tried to get the data in different ways. Using JS DOM. Using POST.
I´ve found some PHP DOM tutorials but them all teach how to modify an static HTML.
Please help me to get the submitted data from each fieldset.
Thanks in advance.
You could format your form names like this.
First question
name="respuestaAlumno[0][]"
name="respuestaAlumno[0][]"
...
name="idPregunta[0]"
name="tipo[0]"
Second question
name="respuestaAlumno[1][]"
name="respuestaAlumno[1][]"
...
name="idPregunta[1]"
name="tipo[1]"
You would end up with three arrays in your $_POST.
Try this
<?php
if(isset($_POST['calificar'])
{
$respuestaAlumno=$_POST['respuestaAlumno'];
//you need respuestaAlumno array to single string
echo $data_to_string=implode(",",$respuestaAlumno);
$count_of_respuestaAlumno=count($_POST['respuestaAlumno']);
for($i=0;$i<=$count_of_respuestaAlumno-1;$i++)
{
echo $data=$respuestaAlumno[$i]."/n";
}
//question id
echo $idPregunta=$_POST['idPregunta'];
echo $tipo=$_POST['tipo'];
//do something
}

Pass selected form input to backend

Consider a simple HTML form like
<form>
<div>
<input type='checkbox' name='selections[]' value='1' />
<input type='text' name="inputs[]" value='' />
</div>
<div>
<input type='checkbox' name='selections[]' value='2' />
<input type='text' name="inputs[]" value='' />
</div>
<div>
<input type='checkbox' name='selections[]' value='3' />
<input type='text' name="inputs[]" value='' />
</div>
</form>
There are three rows, assume only the 2nd, 3rd rows are checked, and all three text inputs are filled with (a, b, c), so in my backend (PHP), I can have two arrays
e.g.
$selections = array(2, 3);
$inputs = array('a', 'b', 'c');
What is the easy way to remove a from the $inputs since the checkbox is not checked? i.e. So I can loop the two arrays more easily.
I'd probably use array_map
$inputs = array_map(function($v) use ($inputs) {
return $inputs[$v - 1];
}, $selections);
Though MingShun's answer will work fine if converted to PHP
You should change your HTML like this:
<form method="post">
<div>
<input type='checkbox' name='data[0][selections]' value='1' />
<input type='text' name="data[0][inputs]" value='' />
</div>
<div>
<input type='checkbox' name='data[1][selections]' value='2' />
<input type='text' name="data[1][inputs]" value='' />
</div>
<div>
<input type='checkbox' name='data[2][selections]' value='3' />
<input type='text' name="data[2][inputs]" value='' />
</div>
<input type="submit"/>
TEST DATA:
<?php
echo '<pre>';
print_r($_POST['data']);
?>
RESULT:
Array
(
[0] => Array
(
[selections] => 1
[inputs] => 1
)
[1] => Array
(
[selections] => 2
[inputs] => 2
)
[2] => Array
(
[selections] => 3
[inputs] => 3
)
)
OR:
Array
(
[0] => Array
(
[inputs] => 1
)
[1] => Array
(
[selections] => 2
[inputs] => 2
)
[2] => Array
(
[selections] => 3
[inputs] => 3
)
)
Now you can loop result and handle.
$selections = array();
$inputs = array();
foreach ($_POST['data'] as $item){
if (!empty($item['selections']) && !empty($item['inputs'])){
$selections[] = $item['selections'];
$inputs[] = $item['inputs'];
}
}
var_dump($selections);
var_dump($inputs);
This answer requires detailed knowledge of what's coming in. Which is rather bad if you want to reuse it.
The following assumptions are being made about the html page:
The row values start from 1
The row values are ascending
The row values are continuous. e.g. 1, 2, 3... not 1, 2, 4...
And here's the code:
$len = count($selections);
for ($i = 0; $i < $len; $i++)
{
if (!in_array($i + 1, $selections))
unset($inputs[$i]);
}

php how to display ALL array items including null value items

I try to list ALL $_POST array items using var_dump (or echo), but null value items are not displayed. If I use var_dump($_POST) null doesn't appears, but if I use var_dump($_Post["nullitem"]) null appears:
<html>
<head>
</head>
<body>
<?php
if ($_POST["submit"]){
var_dump($_POST);
foreach ($_POST as $key => $value) {
echo $key."=>";
echo $value;
echo " - ";
}
echo "<br>";
echo "ck_1 "; var_dump($_POST["ck_1"]);
echo "ck_2 "; var_dump($_POST["ck_2"]);
echo "ck_3 "; var_dump($_POST["ck_3"]);
}
?>
<form action='test.php' method='post' name='form_example' id='test'>
<label for='ck_1'>
<input type='checkbox' value=1 id='ck_1' name='ck_1' />
1 </label>
<label for='ck_2'>
<input type='checkbox' value=1 id='ck_2' name='ck_2' checked='checked' />
2 </label>
<label for='ck_3'>
<input type='checkbox' value=1 id='ck_3' name='ck_3' />
3 </label>
<input type='submit' name='submit' value='Submit' />
</form>
</body>
</html>
Only ck_2 is checked, so this example will output :
array
'ck_2' => string '1' (length=1)
'submit' => string 'Submit' (length=6)
ck_2=>1 - submit=>Submit -
ck_1 null
ck_2 string '1' (length=1)
ck_3 null
How can I include ALL $_POST values in foreach loop (I don't know how many keys nor names in $_POST array)
Thanks for help
Regards
Sorry.
The unchecked checkbox is not set, so is not member of $_POST array and does not appears
A way to get a value for unchecked checkbox is to set an hidden field with same name and id and unchecked value (like 0), so at post time if unchecked hidden value is returned :
<input type="hidden" name="cx1" value="0" />
<input type="checkbox" name="cx1" value="1" />
Thank's Midzai
I think you are including all the values of $_POST array in your foreach. The thing is, if you don't check in the checkbox the $_POST array won't contain it's key nor it's value.
checkbox i believe has only one value possible and that shows only when you "check-in" the checkbox. othervise the $_POST isn't populated with the key. Why you see NULL when you direcly query the $_POST with the specified key name (name of the checkbox that wasn't set) the key does not exist in the $_POST array and to return something it returns NULL.
If you for some obscure reason need to list all the checkboxes that were available to be chcecked in to the user, you can add
<input type='hidden' name='cbNames[]' value='ck_1'/>
<input type='hidden' name='cbNames[]' value='ck_2'/>
<input type='hidden' name='cbNames[]' value='ck_3'/>
for each of the checkboxes on your site and then list through the $_POST['cbNames'] array and query the $_POST for those:
foreach ($_POST['cbNames'] as $cbName)
print $_POST[$cbName];
Try this
<html>
<head>
</head>
<body>
<?php
if ($_POST["submit"]){
echo "<pre>";
print_r(array_filter($_POST["ck_1"]));
echo "</pre>";
}
?>
<form action='test.php' method='post' name='form_example' id='test'>
<label for='ck_1'>
<input type='checkbox' value=1 id='ck_1' name='ck_1[]' />
1 </label>
<label for='ck_2'>
<input type='checkbox' value=1 id='ck_2' name='ck_2[]' checked='checked' />
2 </label>
<label for='ck_3'>
<input type='checkbox' value=1 id='ck_3' name='ck_3[]' />
3 </label>
<input type='submit' name='submit' value='Submit' />
</form>
</body>
</html>

POST arrays not showing unchecked Checkboxes

Having trouble getting my POST arrays to show all checkbox values from my form.
I have a form set up as follows:
<form name='foo' method='post' action=''>
<table>
<tr>
<td class='bla'>Checkbox: <input type='checkbox' name='cBox[]'/></td>
</tr>
<tr>
<td class='bla'>Checkbox: <input type='checkbox' name='cBox[]'/></td>
</tr>
<tr>
<td class='bla'>Checkbox: <input type='checkbox' name='cBox[]'/></td>
</tr>
</table>
</form>
I have a button at the bottom bound to a jquery function that adds 5 more empty rows to the form (hence the arrays for the input name cBox[]).
Now, the problem. Lets say the first checkbox is unchecked, and the last 2 are checked. When I output the values (using PHP print_r for debugging), I will get:
Array ( [0] => on [1] => on)
For some reason, the array does not contain any value for unchecked checkboxes.
I have seen some solutions where a hidden variable is passed with each checkbox, but can this solution be implemented in my situation (using arrays)?
That behavior is not surprising, as the browser doesn't submit any value for checkboxes that are unchecked.
If you are in a situation where you need to submit an exact number of elements as an array, why don't you do the same thing you do when there's an id of some sort associated with each checkbox? Just include the PHP array key name as part of the <input> element's name:
<tr>
<!-- NOTE [0] --->
<td class='bla'>Checkbox: <input type='checkbox' name='cBox[0]'/></td>
</tr>
<tr>
<td class='bla'>Checkbox: <input type='checkbox' name='cBox[1]'/></td>
</tr>
<tr>
<td class='bla'>Checkbox: <input type='checkbox' name='cBox[2]'/></td>
</tr>
That still leaves you with the problem that unchecked boxes will still not be present in the array. That may or may not be a problem. For one, you may really not care:
foreach($incoming as $key => $value) {
// if the first $key is 1, do you care that you will never see 0?
}
Even if you do care, you can easily correct the problem. Two straightforward approaches here. One, just do the hidden input element trick:
<tr>
<td class='bla'>
<input type="hidden" name="cBox[0]" value="" />
Checkbox: <input type='checkbox' name='cBox[0]'/>
</td>
</tr>
<tr>
<td class='bla'>
<input type="hidden" name="cBox[1]" value="" />
Checkbox: <input type='checkbox' name='cBox[1]'/>
</td>
</tr>
And two, which I find preferable, fill in the blanks from PHP instead:
// assume this is what comes in:
$input = array(
'1' => 'foo',
'3' => 'bar',
);
// set defaults: array with keys 0-4 all set to empty string
$defaults = array_fill(0, 5, '');
$input = $input + $defaults;
print_r($input);
// If you also want order, sort:
ksort($input);
print_r($input);
See it in action.
ONE TRICK is to override the checkbox value, if checked. otherwise its value will be 0.
<form>
<input type='hidden' value='0' name="smth">
<input type='checkbox' value='1' name="smth">
</form>
Try
<input type='checkbox' value="XXX" name='cBox[]'/>
<input type='checkbox' value="YYY" name='cBox[]'/>
<input type='checkbox' value="ZZZ" name='cBox[]'/>
Checkboxes work that way. If it is checked, only then the value is posted.
If you are handling dynamic checkbox array, you can try this:
HTML:
<label>
<input type="hidden" name="cBox[]" value="" />
<input type="checkbox" class="checkbox" value="on" />
</label>
<label>
<input type="hidden" name="cBox[]" value="" />
<input type="checkbox" class="checkbox" value="on" />
</label>
<!-- extend -->
Javascript (jQuery):
$(document).on("change", "input.checkbox", function() {
var value = $(this).is(":checked") ? $(this).val() : null;
$(this).siblings("input[name='cBox[]']").val(value);
});
Backend result (If only checked the second one):
// PHP $_POST['cBox']
Array
(
[0] =>
[1] => on
)
In this implement, the checkboxes are used to controller each hidden input in a group.
For displaying page, You can render each inputs pair back by assigning the value into hidden inputs and marking checkboxes as checked.
Try setting a value to each checkbox, of 1 or true.
<input type='checkbox' value='1' name='cBox[1]'/>
that may be why its not sending anything?
In controller:
request()->merge(['cBox' => request()->input('cBox', [])]);

Categories