Core\Arr::withoutNull
Returns a new array with every null value removed.
Core\Arr::withoutNull never changes the array you give it. Every entry that stays keeps its own key. Use Core\Arr::values when you want the keys numbered from "0" again.
The type of the result has no null. An array<?string> gives an array<string>, so you can use the values without a cast. An array<mixed> gives an array<mixed>.
Good to know: only null is removed. The values 0, '', false and [] stay in the result. An array of only null values gives an empty array, and that is not an error.
Parameters
$aarray<?T>The array to removenullvalues from.
Return value
Returns array<T>. The other entries under their own keys, never renumbered. Core\Arr::values renumbers them. For an array<E, T>, the result is an array<E, T> too.
Examples
A form s optional fields
<?nvs// Shows how to keep only the form fields somebody filled in.
// The fields `phone` and `company` were left empty, so their value is `null`.array<?string> $form = [ 'name' => 'Ada', 'phone' => null, 'email' => 'ada@example.com', 'company' => null,];
// `Core\Arr::withoutNull` returns a new array without the `null` values.// The type of the result is `array<string>`, so no cast is needed.array<string> $filled = Core\Arr::withoutNull($form);
// This prints "name: Ada" and "email: ada@example.com".foreach ($filled as string $field => string $value) { echo $field, ': ', $value, "\n";}
// Your own array is not changed, so this prints 4.echo Core\Arr::count($form), "\n";name: Adaemail: ada@example.com4Ids that were not found
<?nvs// Shows how to keep only the results of a lookup that found something.
array<string> $names = ['7' => 'Ada', '9' => 'Ben'];
// The lookup returns `null` for an id that is not in `$names`.array<int> $ids = [7, 3, 9, 5];array<?string> $found = [];foreach ($ids as int $id) { $found[] = $names[$id as string] ?? null;}
// This prints 4. Two of the four values are `null`.echo Core\Arr::count($found), "\n";
array<string> $known = Core\Arr::withoutNull($found);
// This prints "Ada, Ben".echo Core\Str::join($known, ', '), "\n";
// Only `null` is removed. An empty string, 0 and `false` stay,// so this prints 3.echo Core\Arr::count(Core\Arr::withoutNull(['', 0, false, null])), "\n";4Ada, Ben3The keys that stay
<?nvs// Shows which keys the result has. Every entry that stays keeps its own key.
array<?int> $scores = [12, null, 30, null, 7];
array<int> $given = Core\Arr::withoutNull($scores);
// The entries under the keys 1 and 3 are gone. The other keys stay as they// were, so this prints 0, 2 and 4.foreach (Core\Arr::keys($given) as string $key) { echo $key, "\n";}
// `Core\Arr::values` numbers the keys from 0 again. This prints 0, 1 and 2.foreach (Core\Arr::keys(Core\Arr::values($given)) as string $key) { echo $key, "\n";}024012