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

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.

Related

Display contents of $_POST one bye one

Hello I am submitting a form with POST method and I want its contents to be echo'ed one by one apart from the last one. So far I am using
<?php foreach($_POST as $data){
echo $data;
}
?>
which displays the whole array of $_POST, how can I make it using common "for" loop to not echo the last item of the array? It doesnt seem to work
<?php
$length=count($_POST)-1;
for($i=0; $i<$length; $i++) {
echo $_POST[$i];
?>
<br>
<?php } ?>
I am getting 5 errors, undefined offset 0 through 4 where the echo line is present
Do the following:
<?php
$counter = 0;
$lastItemOrder = count($_POST);
foreach($_POST as $value) {
$counter++;
if( $counter !== $lastItemOrder) {
echo $value;
}?>
<br><?php
} ?>
Your loop for just get numerical index like $_POSR[0], $_POST[1]... This just would work if in the HTML the attribute name of the input elements be numerical also, like name="0" and so on.
foreach perform loop on array independently of index, numerical or string.
Try this:
<?php
$counter = 0;
$lastItemOrder = count($_POST);
foreach($_POST as $index => $value) {
$counter++;
if( $counter !== $lastItemOrder) {
echo $index . ": " . $value;
}?>
<br><?php
} ?>
ok now I get it, I didnt know the difference between associative and numeric arrays. I fixed it with an if statement

Obtaining $_SESSION array values and displaying using echo

I have the ff code which stores values inputted in form's textfield to a session array which I named "numbers". I need to display the value of the array but everytime I try echo $value; I get an error Array to string conversion in
I used echo var_dump($value); and verified that all the inputted values are stored to the session array.
My goal is to store the user input to an array everytime the user hits the submit button.
How do I correct this?
<?php
session_start();
?>
<html>
<head>
<title></title>
</head>
<body>
<form method="POST" action="index.php">
<label>Enter a number</label>
<input type="text" name="num" required />
<button type="submit">Submit</button>
</form>
</body>
</html>
<?php
if (isset($_POST["num"]) && !empty($_POST["num"])){
$_SESSION['numbers'][] = $_POST["num"];
foreach($_SESSION as $key => $value){
echo ($value);
}
}
?>
Thank you.
When doing $_SESSION['numbers'][] = $_POST["num"];, you are making $_SESSION['numbers'] an array: so you'll either need to do that differently, or check whether $value within your foreach loop is an array or not.
if (isset($_POST["num"]) && !empty($_POST["num"])){
$_SESSION['numbers'][] = $_POST["num"];
foreach($_SESSION as $key => $value){
if (is_array($value)) {
foreach ($value as $valueNested) {
echo ($valueNested);
}
} else {
echo ($value);
}
}
}
OR
if (isset($_POST["num"]) && !empty($_POST["num"])){
$_SESSION['numbers'] = $_POST["num"];
foreach($_SESSION as $key => $value){
echo ($value);
}
}
The latter is probably what you are actually trying to accomplish.
If you want to echo all entered numbers, your for each cycle should be:
foreach($_SESSION[‘numbers’] as $key => $value) {
echo $value;
}
This is because the $_SESSION[‘numbers’] itself is the array that contains the numbers.
The error is because SESSION[“numbers”] is an array and you can just echo an array. It will throw an error “Array to string converstion”.
Iterate through the array and print it instead.

Echo selected values from an associate array

i dont want to echo the last two values in an associative array, couldn's figure it out, please help.
foreach($_POST as $key => $value){
echo $value;
}
This echoes all the values, i want to echo all but the last 2.
Just count the loops and dont print the value in the last two loops.
$i = 0;
foreach($_POST as $key => $value) {
$i++;
if($i != count($_POST) && $i != count($_POST)-1) {
echo $value;
}
}
It should work to slice the array before you loop it.
<?php
$newArray = array_slice( $_POST, 0, count($_POST)-2);
foreach( $newArray AS $key => $value ) {
echo $value;
}
If you want to keep your $key value, then set the 4th parameter to true to "preserve keys":
http://php.net/manual/en/function.array-slice.php
Maybe this is just an exercise, but I do want to note, in addition, that relying on the exact order of your POST'd elements sounds like a bad design idea that could lead to future problems.
I'd rather do this:
$a = array('a' => 'q','s' => 'w','d' => 'e','f' => 'r');
$arr_count = count($a) - 2;
$i = 1;
foreach($a as $k => $val){
echo $k.' - '.$val.PHP_EOL;
if ($i == $arr_count) break;
$i++;
}
Another alternative solution:
<?php
$tot=count($_POST)-2;
while ($tot--) {
// you can also retrieve the key using key($_POST);
echo current($_POST);
next($_POST);
}

Getting both or one Checkbox value in for each loop

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;
}
}
}
}

Looking for a way to store the result of a form field with dynamic name and id in an array after submit

I'm building a form which has the following fields:
$k = 1;
foreach($ui_fmlSect_pg as $val)
{
$url_arr[] = $val;
echo '<tr>';
echo '<td><input size="1" type="text" name="freq_'.$k.'" id="freq_'.$k.'"
value="'.$udf_fmlS.'"></td></tr>';
++$k;
}
I would like to find a way to add the entered values, that is the content of the variable $udf_fmlS or any manual overwriting, from the *freq_$k* -named input fields into an array, but I'm not sure how to proceed with this, especially as the name and id are dynamically generated.
Thanks in advance for your help
You could do something like this:
$freq = array();
foreach ($_POST as $key => $val) {
// check for submitted data starting with freq_
if (substr($key, 0, 5) == 'freq_') {
// use the number after freq_ as the key and the value as the value
$freq[substr($key, 5)] = $val;
}
}
If I understand correctly, you will have variables like:
$_REQUEST['freq_0']
$_REQUEST['freq_1']
etc. You could do something like:
<?php
$freq_val_arr = array();
foreach($_REQUEST as $key => $val){
if (strpos($key, 'freq') === 0){
$freq_val_arr[] = $val;
}
}
Just change 'file_'.$k to 'file[]' or to 'file[' . $k . ']'

Categories