1

I am getting three values("123","456","789") in array using foreach loop, now i want whenever i am getting value "456" then delete this value from array.how can i do this ? i have tried if loop inside the array when i get 456 but it still not working.`

`

3 Answers 3

2

A better way would be to use array_splice

Then just create a function to wrap it [array_pluck], which plucks out the array item, and updates the original input.

<?php
$input = ["123","456","789"];

function array_pluck(&$array, $key) {
    if (isset($array[$key])) {
        return array_splice($array, $key, 1)[0];
    }
}

echo array_pluck($input, 1); //456

print_r($input);

https://3v4l.org/J42A5

If you're looping over the array, and then you want to remove the items, you could also use a generator.

<?php
$input = ["123","456","789"];

function array_pluck_gen(&$array) {
    foreach ($array as $k => $v) {
        unset($array[$k]);
        yield $v;
    }
}

foreach (array_pluck_gen($input) as $value) {
    echo $value;
}

print_r($input);

Or just unset it.

<?php
$input = ["123","456","789"];

foreach ($input as $key => $value) {
    unset($input[$key]);
    echo $value;
}

print_r($input);
Sign up to request clarification or add additional context in comments.

Comments

0

You can do it like this:

$array = array("123","456","789") ;
$arrFinal = array();
array_walk($array, function($val, $key) use (&$arrFinal){
    if ($val != '456') {
        $arrFinal[$key] = $val;
    }
});
print_r($arrFinal);

Comments

0
$array=array("123","456","789");
foreach($array as $key=>$val){
  if($val=="456"){
    unset($array[$key]);
  }
}
print_r($array);

Comments