I’m new to php and I was wondering how I would be able to create something like a delete button for deleting items in a list that would be generated from a dynamically growing array.
An example of what I mean is this:
<?php
if (isset($_REQUEST['foo']))
{
if (isset($_SESSION['words']))
{
$_SESSION['words'][] = 'added word';
}
else
{
$_SESSION['words'] = array('cat', 'dog', 'you', 'me');
}
foreach ($_SESSION['words'] as $key => &$value)
{
echo "<p>" .
$value .
" - <input type='submit' name='delete_" .
$value .
"' value='Delete Entry' /></p>";
}
if (isset($_REQUEST['clear']))
{
session_destroy();
}
?>
Where, on every button click that gets sent to my script it would echo out the array with the buttons.
I’d like to link the delete buttons to a function that looked something like:
function delete_entry( $index )
{
unset($_SESSION['words'][$index]);
$_SESSION['words'] = array_values($_SESSION['words']);
}
Is what I’m asking even possible?
Your array of words seem to be stored in your session variable, so I’m assuming that you want to remove/add words to it. How about this…?
Have a separate form for each word with a hidden field saying what the word is:
So in the for loop:
echo "<form><p>".$value." - <input type='submit' value='Delete Entry' /></p><input type=\"hidden\" name=\"delword\" value=\"".$value."\"/></form>";if(isset[$_REQUEST['delword']])remove it from the session array (do this before you do your echoing for loop. (You could use array_search to find the element, then run unset as you suggested)Let me know if you want me to elaborate on this suggestion.