• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 838
  • Last Modified:

Remove element from an array.

Cannot see the wood for the trees, so this is going to be some EASY points!

I have a dynamic array; i.e. at RUNTIME, values are added and removed.

Well, added is OK.

$a_Array[] = 'value';

By using in_array() I know if the value is already in the array.

How do I remove the value from the array? I have a stupidly convoluted way...

Get the key of the value and then unset that element.

$a = array('one','two',4 => 'three', 3 => 'four'); // NOT a typo!!!!
unset($a[reset(array_keys($a, 'three', True))]);

This is OK, the output is ...

array (
  0 => 'one',
  1 => 'two',
  3 => 'four',

but ...

Strict Standards: Only variables should be passed by reference on line 3

So, I suspect there is really a array_remove(&$array, $value) function SOMEWHERE.
Richard Quadling
Richard Quadling
3 Solutions
Aamir SaeedCommented:
try something like

    * Remove a value from a array
    * @param string $val
    * @param array $arr
    * @return array $array_remval
    function array_remval($val, &$arr)
          $array_remval = $arr;
              if (is_numeric($i)) {
                  $array_temp  = array_slice($array_remval, 0, $i );
                $array_temp2 = array_slice($array_remval, $i+1, count($array_remval)-1 );
                $array_remval = array_merge($array_temp, $array_temp2);
          return $array_remval;

$stack=Array('apple','banana','pear','apple', 'cherry', 'apple');
array_remval("apple", $stack);

//output: Array('banana','pear', 'cherry')
Using unset is the standard way to remove an item from an array according to the documentation:


Cornelia YoderArtistCommented:
Use array_diff( ) or one of it's variations (depending on exactly how you want to specify the element to be removed).


Richard QuadlingSenior Software DeveloperAuthor Commented:

Ok. That was WAY too easy!

  * array array_remove ( array input, mixed search_value [, bool strict] )
function array_remove(array &$a_Input, $m_SearchValue, $b_Strict = False)
      $a_Keys = array_keys($a_Input, $m_SearchValue, $b_Strict);
      foreach($a_Keys as $s_Key)
      return $a_Input;
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Hire Technology Freelancers with Gigs

Work with freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely, and get projects done right.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now