0

Remove those array indexes whose value is 1

array (1=>1,2=>2,3=>1,4=>1,5=>3,6=>1);

result array as

array(2=>2,5=>3);

is there is a direct function in php? like

unset(key($a,1));
0

5 Answers 5

2

One liner, using array_diff as

$your_array = array_diff ( $your_array, [1] );

Sign up to request clarification or add additional context in comments.

Comments

2

look to use array_filter()

$myArray = array (1=>1,2=>2,3=>1,4=>1,5=>3,6=>1);

$myArray = array_filter(
    $myArray,
    function($value) {
        return $value !== 1;
    }
);

4 Comments

You answer gives error "Parse error: syntax error, unexpected T_FUNCTION on line 7".
@FatalError - what version of PHP are you using? I'm guessing < 5.3.0 - Demo perhaps time you should upgrade to a supported version of PHP
@MarkBaker sorry there was version problem.
@FatalError Welcome in 2015, this year PHP 7 gets probably released, so get your PHP up and running with upgrading it :)
0

Using array_search() and unset, try the following:

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

Comments

0

Loop through it, check and unset -

foreach($array as $k => $v) {
    if($v == 1) {
        unset($array[$k]);
    }
}

Or use array_filter()

$newArr = array_filter($array, function($v) {
    return ($v != 1);
});

Or you can use array_flip() for some trick -

$temp = array_flip($array);
unset($temp[1]);
$array = array_flip($temp);

Comments

0

You can also use the array_flip and can use the below code:

<?php
  $arr = array(1=>1,2=>2,3=>1,4=>1,5=>3,6=>1);
  $arr1 = array_flip($arr);
  unset($arr1[1]);
  $arr = array_flip($arr1);
  print_r($arr);
?>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.