Php removes one element from an array

Let's say I have an array:

$before = array(1,2,3,3,4,4,4,5) 

How to delete only one event, for example, "3"?

 $after = array(1,2,3,4,4,4,5) 

(I do not know where in the array this number will be)

+4
source share
5 answers

You can use various methods, depending on what exactly you are trying to do:

  • Find the index using array_search() and then unset() .
  • If you know the index, use array_splice() to replace it with nothing.
  • Use array_filter() with a custom callback.
+5
source

The general routine is simply to populate the $ reducedValues ​​array with the values ​​you want to reduce to single.

 $before = array(1,2,2,2,3,3,4,4,4,5,5); $reduceValues = array(3,5); $toReduce = array_fill_keys($reduceValues,TRUE); $after = array_filter( $before, function($data) use ($reduceValues,&$toReduce) { if (in_array($data,$reduceValues)) { if ($toReduce[$data]) { $toReduce[$data] = FALSE; return TRUE; } return FALSE; } return TRUE; } ); var_dump($after); 
+1
source

Is this the functionality you are looking for?

http://php.net/manual/en/function.array-filter.php

0
source

If you know the order of the specific item you want to remove, you can use something like

  unset $before[2] 
0
source

There are several ways to do what you ask. Which one you should use depends on the context of its use, as well as the exact result. I prefer array_splice () as it supports array numbering. If you need the simplest method, I suggest unset () . If you are looking for a way to eliminate duplicates, use array_unique () . With the last two, if you need to renumber them back as they were, use array_values ​​() . If you do not know the index of the value to be deleted, you can use one of the above in combination with array_search () . If you need a more advanced filter, use array_filter () .

 <?php header('Content-Type: text/plain'); $original = array(1,2,3,3,4,4,4,5); echo "ORIGINAL:\n"; print_r($original); echo "\n\n"; echo "Using array_splice():\n"; $new = $original; array_splice($new, 3, 1); print_r($new); echo "\n\n"; echo "Using array_unique() to remove dupes:\n"; $new = array_unique($original); $new = array_values($new); print_r($new); echo "\n\n"; echo "Using unset:\n"; $new = $original; unset($new[3]); $new = array_values($new); print_r($new); echo "\n\n"; echo "Using array_search & unset:\n"; $new = $original; unset($new[array_search('3', $new)]); $new = array_values($new); print_r($new); echo "\n\n"; ?> 
0
source

Source: https://habr.com/ru/post/1403150/


All Articles