Removing a specific element in an array

Asked

Viewed 74,116 times

10

I have the following array

$input = array("item 1", "item 2");

But as it is dynamic, items can change

$input = array("item 2", "item 4");

$input = array("item 4");

It is possible to use the array_splice to remove, if any, a specific element (item 2) from the array?

5 answers

22


If you know the position in the array can use the unset(); directly

unset($input[0]);

To be clearer:

$input = array("item 2", "item 4");
var_dump($input);
unset($input[0]);
var_dump($input);

gives:

array(2) {
  [0]=>
  string(6) "item 2"
  [1]=>
  string(6) "item 4"
}
array(1) {
  [1]=>
  string(6) "item 4"
}

If you don’t know the position in the array you have to go through the array or use array_search() first and then the unset()

$key = array_search('item 2', $input);
if($key!==false){
    unset($input[$key]);
}

Example:

$input = array("item 2", "item 4");
$key = array_search('item 2', $input);
if($key!==false){
    unset($input[$key]);
}
var_dump($input);

that gives

array(1) {
  [1]=>
  string(6) "item 4"
}
  • Your example using array_search worked for me. But when I was used with the array generated by Wordpress (get_the_category( $post->ID ), it continues printing the two categories.

  • @marcelo2605 get_the_category( $post->ID ) is the function that gives the value you want to remove? or is the $post that is your array?

  • is the function that generates my array: $input = get_the_category( $post->ID );

  • 1

    @marcelo2605 what you get when you do var_dump(get_the_category( $post->ID ))?

  • I found the answer here: http://wordpress.stackexchange.com/a/144617/38553 I added your if($key!== false){

  • @marcelo2605 this answer is basically the same as mine. I got it to work?

  • 1

    Yes, I did. Thank you.

Show 2 more comments

6

You can use "array_diff" to remove one or more elements from an array by values:

$input = array("item 1", "item2", "item3", "item4");

$remover = array("item2");

$resultado = array_diff($input, $remover)

$result would be an array with only "item 1", "item3", "Item4".

But this is only true if you want to remove any occurrence of the same value in your array, that is, if there are two elements with "item2", both will be removed.

1

And if the array you search for is multidimensional, a complement to the answer do @Sergio, would be a function originated in the comments of the PHP manual (but today, unfortunately lost) that allows searching recursively using the PHP Iterators themselves:

/**
 * Searches value inside a multidimensional array, returning its index
 *
 * Original function by "giulio provasi" (link below)
 *
 * @param mixed|array $haystack
 *   The haystack to search
 *
 * @param mixed $needle
 *   The needle we are looking for
 *
 * @param mixed|optional $index
 *   Allow to define a specific index where the data will be searched
 *
 * @return integer|string
 *   If given needle can be found in given haystack, its index will
 *   be returned. Otherwise, -1 will
 *
 * @see http://www.php.net/manual/en/function.array-search.php#97645 (dead)
 */
function search( $haystack, $needle, $index = NULL ) {

    if( is_null( $haystack ) ) {
        return -1;
    }

    $arrayIterator = new \RecursiveArrayIterator( $haystack );

    $iterator = new \RecursiveIteratorIterator( $arrayIterator );

    while( $iterator -> valid() ) {

        if( ( ( isset( $index ) and ( $iterator -> key() == $index ) ) or
            ( ! isset( $index ) ) ) and ( $iterator -> current() == $needle ) ) {

            return $arrayIterator -> key();
        }

        $iterator -> next();
    }

    return -1;
}

To use just inform the array where to search and what to look for. If the array structure is more or less known, you can inform a third argument so that the search is restricted only to sub-arrays with that key.

0

Well I was looking for a solution for something similar and what I did to solve was to scan the array in a foreach and remove the variable found with unset(); and create a new array ' $result' without this variable. An example from below.

$input = array 0 => ("item1", "item2", "item3", "item4")
         array 1 => ("item1", "item2", "item3", "item4")

$contador=0;

foreach ($input as $i):
        if(isset($i['item1'])): unset($i['item1']);  endif;
        $resultado[$contador++]=$i;
endforeach;

$resultado = array 0 => ( "item2", "item3", "item4")
             array 1 => ( "item2", "item3", "item4")

obs. I am new Aki and in programming tbm I believe it is not the best solution but solved in the case ;)

-2

You can use it like this:

let vet = ["Italo", "Joao", "Maria"];

let index = vet.indexOf("Italo")

if(index > -1) {
  vet.splice(index,1)
}

The indexOf will search your vector and return 0 the value is found, and -1 if not found. Attention that is case sensitive.

Then inside the if the splice removes the element at the passed position.

  • 1

    The question has the PHP tag, not Javascript. While this answer can work in Javascript, it is not a valid answer because it does not solve the problem in PHP.

Browser other questions tagged

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