avatar
remove invalid elements from array in PHP PHP

• Using `foreach` and `unset` function

$arr = array(<Data>);
$samples = array();
foreach ($arr as $key => $item) {
    $obj = $this->fruitRepository->findByField('id', $item);
    if (null == $obj) {
        unset($arr[$key]);
    } else {
        $samples[] = $obj[0];
    }
}

• Using `array_filter()` function.

$arr = array(<Data>);
$samples = array_filter(array_map(function($item) {
    $obj = $this->fruitRepository->findByField('id', $item);
    return $obj ? $obj[0] : null;
}, $arr));

• Using `array_diff` function

$arr = array(<Data>);
$invalid = array();
foreach ($arr as $key => $item) {
    $obj = $this->fruitRepository->findByField('id', $item);
    if (null == $obj) {
        $invalid[] = $item;
    }
}
$samples = array_diff($arr, $invalid);
You need to login to do this manipulation!