0

i'm trying to create a simple system to add and remove element of an array. I already did it, but i want to know how to add or remove an item from a specific position. For example: I want to remove the 2nd element of an array and add another to the 4º position?

I can only do this but to add on the beggining or at the end of the array.

This is my code so far:

<form method="post" action="<?php $_SERVER['REQUEST_URI']; ?>">
<input type="text"   name="arr" /><br />
<input type="radio"  name="op" value="push" /> add to the end<br />
<input type="radio"  name="op" value="merge" /> add to start<br />
<input type="radio"  name="op" value="pop" /> remove from the end<br />
<input type="radio"  name="op" value="shift" /> remove from the start<br />
<input type="submit" value="Exec" />
</form>

<?php

if(!empty($_POST['op'])){
  $op = $_POST['op'];
  $marcas = $_SESSION['array'];

  if($op == "push"){
    array_push($marcas,$_POST['arr']);
  }elseif($op == "pop"){
    array_pop($marcas);
  }elseif($op == "merge"){
    $ar2 = array($_POST['arr']);

    $marcas = array_merge($ar2,$marcas);
  }else{
    array_shift($marcas);
  }
  $_SESSION['array'] = $marcas;
}
else{
  $_SESSION['array'] = array ("Fiat","Ford", "GM", "VW"); 
}
print_r($_SESSION['array']);
?>
2

1 Answer 1

1

you'll want to use array_splice() for removing/adding/replacing elements in arbitrary positions in an array.

add/remove examples:

// sample data
$a = [1, 2, 3, 4, 5];

// insert 1.5 after 1, before 2
array_splice($a, 1, 0, 1.5);

// $a is now [1, 1.5, 2, 3, 4, 5]

// remove 4
array_splice($a, 4, 1);

// $a is now [1, 1.5, 2, 3, 5]
Sign up to request clarification or add additional context in comments.

1 Comment

But how am i suposed to add this to my code, so it appear as an option inside the form to check and add/remove.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.