Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php appending array

Tags:

php

OK so I have changed my code to look more like what you have all suggested, but the actual append still does not happen. It simply changes the single value in the array to be the new value being passed in instead of an actual append.

if(isset($_POST['addtag']) && isset($_POST['tagname']))
{
  if(isset($_POST['tags']))
  {
    $_POST['tags'][] = $_POST['tagname'];
  }
  else
  {
    $_POST['tags'] = array($_POST['tagname']);
  }
}

The reason I check to see if the 'tags' variable has been set is because there's no guarantee that it is an array yet so I don't take the chance of using it like one until I initialize it with an array value.

Here's what happens:
1. I visit the page for the first time.
2. I add a tag ('tag1')
3. The page refreshes and reflects that the 'tags' variable has a size of 1 and displays 'tag1'
4. I add another tag ('tag2')
5. The page refreshes and reflects that the 'tags' variable has a size of 1 and displays 'tag2'

I say "refreshes" because this is the only term I know that specifies that the action of the form points to the page it is located on.

like image 928
LunchMarble Avatar asked Jun 13 '26 09:06

LunchMarble


1 Answers

Regarding your update:

$_POST is not persistent between request. It will only contain values the HTML pages sends to the server. So as long as you don't send a list of every created tag in each request, $_POST['tags'] will always be empty.

I think what you want is a session.

You also should read about form handling in PHP.


The only thing you have to do is:

$appendedTags = $_POST['tags'];
$appendedTags[] = $_POST['tagname'];

or if you really want to use $_POST['tags'] in further processing (which you shouldn't, I think you have a false concept of $_POST in your head (because you write in a comment post out.... what does this mean?)):

$_POST['tags'][] = $_POST['tagname'];

Some remarks on your code:

  • In PHP, you don't have to initialise the length of an array. You can add as many elements as you want. You can think of it as a list or table.

  • Your for loop just copies all values from one array to another. You can achieve the same by just assigning the array contained in $_POST['tags'] to a new variable.

  • If you don't specify an index, the next highest index will be chosen for a new value.

You really should read about arrays in PHP.

like image 154
Felix Kling Avatar answered Jun 14 '26 23:06

Felix Kling



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!