Obtaining $_SESSION array values and displaying using echo - php

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.

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.

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

PHP - get proper value type and encode the right JSON string

I have a php code as a test like this:
$myObj->string = "myString";
$myObj->number = 111;
$objects = json_encode($myObj);
echo $objects;
the echo i get shows 111 as a number, not a string, which is what i need:
{“string”:”myString”,”number”:111}
But, if i send a form like the one one below to my save.php file, the 111 value gets wrapped into “”, so it becomes a string.
My form:
<form action="save.php">
<input type="text" name="string">
<input type="number" name="number">
<input type="submit">
</form>
the values i type in the input areas are:
myString
111
My save.php file:
foreach($_GET as $key => $value) {
$objects->$key = $value;
}// ./ foreach
$objs = json_encode($objects);
echo $objs;
the echo i get is:
{“string”:”myString”,”number”:”111”}
which is not right since i need to get a number, so it should be like: “number”:111
What am i missing, or doing wrong?
Thanks!
You can use:
$objs = json_encode($objects, JSON_NUMERIC_CHECK);
JSON_NUMERIC_CHECK
Encodes numeric strings as numbers. Available since PHP 5.3.3. http://php.net/manual/en/json.constants.php
You can first check if the string is numeric, and then force it to be handled accordingly:
foreach($_GET as $key => $value)
{
if( is_numeric($value) )
{
$objects->$key = (float) $value;
}
else
{
$objects->$key = $value;
}
}
$objs = json_encode($objects);
echo $objs;
Assuming your PHP version is > 5.3.2, you can also use the JSON_NUMERIC_CHECK constant on json_encode():
foreach($_GET as $key => $value)
{
$objects->$key = $value;
}
$objs = json_encode($objects, JSON_NUMERIC_CHECK);
echo $objs;

Array returns "Array"

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

PHP | Get input name through $_POST[]

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?

Categories