Jump to content

array_push() not adding anything to array


pcristian43

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
Share on other sites

@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.

Link to comment
Share on other sites

@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
Link to comment
Share on other sites

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
Link to comment
Share on other sites

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
Link to comment
Share on other sites

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>
Link to comment
Share on other sites

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
}
Link to comment
Share on other sites

@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.

Link to comment
Share on other sites

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.