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']);
?>
Michael Berkowski
  • 253,311
  • 39
  • 421
  • 371
celsomtrindade
  • 3,931
  • 14
  • 48
  • 105
  • insert at any position: http://stackoverflow.com/questions/3797239/insert-new-item-in-array-on-any-position-in-php delete from any position: http://stackoverflow.com/questions/369602/delete-an-element-from-an-array – Digital Chris Jan 29 '14 at 02:09
  • Check out this answer here about array_splice: http://stackoverflow.com/questions/3797239/insert-new-item-in-array-on-any-position-in-php – The Ryan Jan 29 '14 at 02:12

1 Answers1

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]
noodlehaus
  • 11
  • 1