This is my first time trying to create an array but it's not going so well.
My code scans every $_POST in a form when pressing a submit button below an input field. What I wanted it to do was to only fetch the content of a "filled" input. Well life's full of disappointments so then I tried to remove all the empty array elements. But instead of doing that, it echos the word "Array".
I've always been bad at arrays, ever since my C# days and I've never known why because they always look so simple. If anybody can tell me what I'm doing wrong, I'd appreciate it.
PHP code that goes above the <html>
<?php
//This is what I've tried before
//$klant = array();
foreach($_POST as $k => $v) {
if (substr($k,0,10) == 'newRecord') {
$id = substr($k,10);
$klant[] = $v;
$klant = array_filter($klant);
echo $klant;
}
}
?>
Markup
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<table>
<?php
$query = ("select * from table1");
$result = mysqli_query($con, $query) or die (mysqli_error());
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){
$id = $row['rowid'];
?>
<tr><!--There are multiple rows, that's why I'm using foreach($_POST as $k => $v)-->
<td>
<input class="newRecord<?php echo $id; ?>" type="text" name="newRecord<?php echo $id; ?>" />
<a href="?record=<?php echo $id; ?>">
<button class="saveRecord<?php echo $id; ?>" name="saveRecord<?php echo $id; ?>">Save</button>
</a>
</td>
</tr>
<?php } ?>
</table>
</form>
You cannot echo arrays use print_r or var_dump
for Pretty-printing arrays try this
echo "<pre>";
print_r($your_array);
echo "</pre>";
I believe this is what you want!
<?php
$klant = array();
foreach($_POST as $k => $v) {
if (substr($k,0,10) == 'newRecord' && trim($v)) {
$id = substr($k,10);
$klant[$id] = $v;
}
}
echo "<pre>";var_dump($klant);echo "</pre>";
?>
But I am not that confident that I understand the question clearly. Can you clarify a bit more than this(if this is not what you desire)?
Change this :
echo $klant;
To this :
print_r($klant);
Or this :
var_dump($klant);
echo is just for strings, print_r and var_dump will echo anything (strings, arrays, objects etc).
EDIT for OP EDIT :
This will remove anything that is empty inside the array :
foreach ($klant as $key => $value)
if (empty($value))
unset($klant[$key]);
print_r($klant);
Try this
foreach($_POST as $k => $v) {
if (substr($k,0,10) == 'newRecord') {
$id = substr($k,10);
$klant[] = $v;
}
}
var_dump($klant);
Related
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
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.
I need some information regarding whether or not we can put more than two variable in a foreach loop. Do keep in mind I'm still a complete newbie :D
For example, I'm getting the data of the variable from a database with comma's
<?php
while($segment = $results->fetchRow()) {
$seg = explode(',', $segment['name']);
$section = explode(',', $segment['sek_id']);
$array = array_combine($seg, $section);
foreach($array as $out => $key){
if($out != ""){
?>
<option value="<?php echo $key; ?>"><?php echo $out; ?></option>
and here I managed to put two variables into my foreach loop.
Is there any way with it while still using a foreach loop? Like maybe if I have an 'id=""' where I would put the id's that is in comma's in it?
You can use following way.
<?php
$results = $results->fetchRow();
foreach($results as $result)
{
if(!empty($result['name']))
{
?>
<option value="<?php echo $result['sek_id']; ?>">
<?php echo $result['name']; ?>
</option>
<?php
}
}
<?php
That will be great if you can provide result of $results->fetchRow();
Let me know in case of any query.
I have tried this simple code to generate an array which will send and a form data in post method. what is the way of receiving this array in desired page? Here is the code:
$serial = 0;foreach ($results as $row) {$serial = $serial + 1;
Html:
<input class="float-lt" type="radio" value=""; ?>" name="question-<?php echo "{$serial}"; ?>[]"/>
<input class="float-lt" type="radio" value=""; ?>" name="question-<?php echo "{$serial}"; ?>[]"/>
$used_serials = $_POST['serials];
foreach( $used_serials AS &$serial ){
$key = 'question-'.$serial;
$wanted_serial_pack = $_POST[$key];
}
OR better use an multidimensional Array structure like:
name="question['serials'][$serial]"
Then you can loop over $_POST['serials]
PHP
$serial = 0;
$inputs = array();
foreach ($results as $row) {
$serial = $serial + 1;
$inputs[] = "<input name=\"question['keys']['{$serial}'][]\"/>";
}
template.php:
echo implode(' ',$inputs);
Submit.php
$results = $_POST['keys];
foreach($results as $serial_array){
var_dump($serial_array);
}
Something like this may help.
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.