Jump to content

Recommended Posts

I am trying to add new elements to an empty array using a form and submit button and the code is not adding anything from it. Here is the code I use:

<!DOCTYPE html>
<html>
	<head>
		<title>
			
		</title>
	</head>
	<body>
		<div class="site">
			<div class="menu">
				
			</div>
			<div class="head">
				
			</div>
			<div class="content">
				<form>
					<input type="text" value="" name="add"/><br/>
					<input type="submit" value="Add" name="submit"/>
				</form>
			</div>
			<div class="footer">
				
			</div>
		</div>
	</body>
</html>
<?php
$submit = $_POST["submit"];
$field = $_POST["add"];
$list = array();
if($submit){
	$psh = array_push($list,$field);
	
	echo $list;
}
	
?>

Any idea why is it not working?
 

Link to comment
https://forums.phpfreaks.com/topic/293069-array_push-not-adding-anything-to-array/
Share on other sites

Since you didn't include a METHOD in your <form> tag, the default is used which is GET. You're checking POST.

 

You are also trying to "echo $list" and $list is an array, you can't echo arrays. Use var_dump() or print_r() on arrays.


<form name="form_name" method="post" action="">


<?php

$your_array = array();

if(isset($_POST['add']) && !empty($_POST['add'])
{

if(array_push($your_array, trim($_POST['add'])
{
print_r($your_array);
}
else
{
"failed to push item on array."
}

@hansford:

 

Why check if $_POST['add'] is empty() then trim() it? A value of any non-printable character, e.g. a space, would pass the empty() check but would then be empty when added to the array.

 

Also, I'm not sure the condition to check if array_push failed is appropriate. Per the manual array_push() returns

 

 

Returns the new number of elements in the array.

 

So, if nothing was added and the array was not empty to begin with it would pass that condition even if nothing was added. In this specific case that might work since we are always starting with an empty array, but it would seem to be bad practice.

@Psycho

 

Running a test:

$arg = array();
$v = "";
if(isset($v))
{
    echo 'empty string allowed to pass <br />';
}
// result: 'empty string allowed to pass'

if(isset($v) && !empty($v))
{
    echo 'empty string slipped through <br />';
}
else
{
   echo 'empty string not allowed to pass <br />';
}
// result: 'empty string not allowed to pass';

I had a problem with this many years ago and when I began doing this - I haven't had a problem since. Let me know your opinion.

Trim - I trim all user input. "  People do this  ";

With array_push, I used the return value improperly - thanks for the heads up. I personally wouldn't use it for this because it's slow and unnecessary.

$your_array = array();

$your_array[] = 'some value';
$your_array[] = 'another value';
Edited by hansford

I would trim() the value first - then do an empty() validation. But, that can be problematic too because empty() will return true for values such as "0", "0.0". If the character "0" is a valid input, then using empty() would flag the value as invalid. If "0" or "0.0" is not considered valid, then you could use it. But, if you have a field that can contain any number of arbitrary characters (at least one) then you could simply do this

 

$var = $_POST['foo'];
if($foo == '')
{
    //Invalid input
}

 

But, I typically only have a simple non-empty check for things such as a name field. Many fields (email, age, dates, etc.) will have much more validation anyway.

  • Like 1
if(isset($_POST['add']) && trim($_POST['add']) != '') {  

That should be sufficient to ensure is not empty data

Any data type checking or filtering might be nice

 

You may even want to check that a value doesn't already exist in the array

Can use the same method to ensure is now added to the array.

if(!in_array($field,$list, true)){
        array_push($list, $field);
    }

Additionally you don't echo an array, you need to loop it

foreach($list as $values){
    echo "$values <br />";
}

The new array will always be set empty and a new single value added in the form unless saved into sessions or a database, did something else with it.

 

So all together

<!DOCTYPE html>
<html>
<head>
<title>
</title>
</head>
<body>
<div class="site">
<div class="menu">
</div>
<div class="head">
</div>
<div class="content">
<form action="" method="post">
<input type="text" value="" name="add"/><br/>
<input type="submit" value="Add" name="submit"/>
</form>

<?php
//create array
$list = array();

//check is set and not blank
if (isset($_POST['add']) && trim($_POST['add']) != '') {
   
//assign variable
$field = trim($_POST['add']);
   
    //see if doesn't already exist in the array
    if (!in_array($field, $list, true)) {
        //add it to the array
        array_push($list, $field);

        //check if it added to array
        if (!in_array($field, $list, true)) {

            echo "not added <br />";

        } else {
           
            echo "added <br />";
           
        }
       
       
    } else {
       
        echo "already existed <br />";
       
    }
   
}

//loop and show results from array if not empty
if (!empty($list)) {
   
    foreach ($list as $values) {
        echo "$values <br />";
    }
   
}
?>

</div>
<div class="footer">
</div>
</div>
</body>
</html>
Edited by QuickOldCar
  • Like 1

An example saving them into a session

<?php
session_start();
?>
<!DOCTYPE html>
<html>
<head>
<title>
</title>
</head>
<body>
<div class="site">
<div class="menu">
</div>
<div class="head">
</div>
<div class="content">
<form action="" method="post">
<input type="text" value="" name="add"/><br/>
<input type="submit" value="Add" name="submit"/>
</form>

<?php
//create array
if(!$_SESSION['list']){
$_SESSION['list'] = array();
}


//check is set and not blank
if (isset($_POST['add']) && trim($_POST['add']) != '') {
   
//assign variable
$field = trim($_POST['add']);
   
    //see if doesn't already exist in the array
    if (!in_array($field, $_SESSION['list'], true)) {
        //add it to the array
        //array_push($_SESSION['list'], $field);
		//or
		$_SESSION['list'][] = $field;

        //check if it added to array
        if (!in_array($field, $_SESSION['list'], true)) {

            echo "not added <br />";

        } else {
           
            echo "added <br />";
           
        }
       
       
    } else {
       
        echo "already existed <br />";
       
    }
   
}

//loop and show results from array if not empty
if (!empty($_SESSION['list'])) {
echo "<h2>List</h2>";
    foreach ($_SESSION['list'] as $values) {
        echo "$values <br />";
    }
   
}
?>

</div>
<div class="footer">
</div>
</div>
</body>
</html>

I would trim() the value first - then do an empty() validation. But, that can be problematic too because empty() will return true for values such as "0", "0.0". If the character "0" is a valid input, then using empty() would flag the value as invalid. If "0" or "0.0" is not considered valid, then you could use it. But, if you have a field that can contain any number of arbitrary characters (at least one) then you could simply do this

$var = $_POST['foo'];
if($foo == '')
{
    //Invalid input
}

But, I typically only have a simple non-empty check for things such as a name field. Many fields (email, age, dates, etc.) will have much more validation anyway.

 

I goofed. That code should have been

 

$var = trim($_POST['foo']);
if($foo == '')
{
    //Invalid input
}

@Psycho

 

Actually, you goofed twice lol.

 

You trim the $_POST variable and assign it to $var.

But then check $foo for the empty string. 

Anyways, it happens - we get what you are saying.

And QuickOldCar posted something similar, so it seems to be the the acceptable way of handling it.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.