Remove array element

Asked

Viewed 1,860 times

1

Good afternoon,

How can I remove only one specific element of the array

$produto = Array([0] => Array("ID" => "12", "Nome" => "Produto1", "Valor" => "45,50") [1] => Array("ID" => "13", "Nome" => "Produto2", "Valor" => "45,90"));

In this case, the client will inform the Name or ID of the array and want to delete it.

2 answers

1


If you want to remove the Array by id or name and not by index of the array you need to search for this value and return its index, php has a native function for this, the array_search, then just give unset by passing the key you received from this function.

Example:

$produto = array(array("ID" => "12", "Nome" => "Produto1", "Valor" => "45,50"),
    array("ID" => "13", "Nome" => "Produto2", "Valor" => "45,90"));

 $key = array_search('Produto1', $produto); // Encontra index do Produto1

unset($produto[$key]); // Remove do Array

var_dump($produto); // Array sem o indice do Produto1
  • Friend, the array_search function is not bringing the key I need...

  • @Lucasaugust of a debug in the function, it returns correctly the Dice, look at the example running online: https://ideone.com/EJz69S

  • Really, it worked after that. Thank you.

0

unset($produto[0])

Where what’s in square brackets is the index.

Or search for the value in the array, find the key and remove.

$key = array_search($string, $array);
if($key! == false){
    unset($array[$key]);
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.