• We just launched and are currently in beta. Join us as we build and grow the community.

Adding and Deleting Item(s) in Array using PHP

NotALeeecher

Anime University Lecturer
N Rep
0
0
0
Rep
0
N Vouches
0
0
0
Vouches
0
Posts
120
Likes
176
Bits
2 MONTHS
2 2 MONTHS OF SERVICE
LEVEL 1 500 XP
In my previous tutorial, I've created the Basic Array Functions. To follow up the tutorials about array, I've created another which will give you knowledge on how to add and delete item/s in array. This tutorial does not include a good design but will give you idea on the topic.

Creating our Form and Script

We create our add form, delete form and our scripts in adding and deleting items. To create the page, open your HTML code editor and paste the code below after the tag. We name this as "index.php".

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <title>Adding and Deleting item/s in Array using PHP</title>
  5. </head>
  6. <body>
  7. <h3>Adding and Deleting item/s in Array using PHP</h3>
  8. <?php
  9. $my_array

    =

    array

    (

    'apple'

    ,

    'orange'

    ,

    'strawberry'

    )

    ;
  10. ?>
  11. <label>Original Array:</label> <?php

    print_r

    (

    $my_array

    )

    ;

    ?>

    <br><br>
  12. <form method="POST">
  13. <label>Add Item to Array:</label> <input type="text" name="add_array">
  14. <input type="submit" name="add" value="Add to Array">
  15. <form>

  16. <form method="POST">
  17. <label>Delete an Item from Array:</label> <input type="text" name="delete_array">
  18. <input type="submit" name="delete" value="Delete from Array">
  19. <form>
  20. <br><br>
  21. <?php
  22. if

    (

    isset

    (

    $_POST

    [

    'add'

    ]

    )

    )

    {
  23. $add

    =

    $_POST

    [

    'add_array'

    ]

    ;
  24. array_push

    (

    $my_array

    ,

    $add

    )

    ;
  25. echo

    "Added a new item: "

    .

    $add

    .

    "<br>"

    ;
  26. print_r

    (

    $my_array

    )

    ;
  27. }
  28. if

    (

    isset

    (

    $_POST

    [

    'delete'

    ]

    )

    )

    {
  29. $delete

    =

    $_POST

    [

    'delete_array'

    ]

    ;
  30. if

    (

    (

    $key

    =

    array_search

    (

    $delete

    ,

    $my_array

    )

    )

    !==

    false

    )

    {
  31. unset

    (

    $my_array

    [

    $key

    ]

    )

    ;
  32. }
  33. echo

    "Deleted an item: "

    .

    $delete

    .

    "<br>"

    ;
  34. print_r

    (

    $my_array

    )

    ;
  35. }

  36. ?>
  37. </body>
  38. </html>


Download
You must upgrade your account or reply in the thread to view hidden text.
 

452,292

323,526

323,535

Top