note 126402 added to function.array-filter

From: Date: Wed, 08 Sep 2021 17:24:42 +0000
Subject: note 126402 added to function.array-filter
Groups: php.notes 
Request: Send a blank email to php-notes+get-216931@lists.php.net to get a copy of this message
Depending on the intended meanings of your "empty" array values, e.g., null and empty string, vs. an integer 0 or a boolean false, be mindful of the result of different filters. <?php declare(strict_types=1); $array = array( 'null' => null, 'nullstring' => '', 'intzero' => 0, 'stringzero' => '0', 'false' => false, 'stringfalse' => 'false', ); // Removes null, null-string -- but also FALSE! $filtered1 = array_filter( $array, 'strlen' ); // Removes only null. $filtered2 = array_filter( $array, function( $v ) { return !is_null( $v ); } ); // Removes null and null-string. Keeps FALSE and 0. $filtered3 = array_filter( $array, function( $v ) { return !( is_null( $v) or '' === $v ); } ); var_dump( $array, $filtered1, $filtered2, $filtered3 ); ?> Results in: array (size=3) 'intzero' => int 0 'stringzero' => string '0' (length=1) 'stringfalse' => string 'false' (length=5) array (size=5) 'nullstring' => string '' (length=0) 'intzero' => int 0 'stringzero' => string '0' (length=1) 'false' => boolean false 'stringfalse' => string 'false' (length=5) array (size=4) 'intzero' => int 0 'stringzero' => string '0' (length=1) 'false' => boolean false 'stringfalse' => string 'false' (length=5) ---- Server IP: 45.112.84.4 Probable Submitter: 45.112.85.242 (proxied: 206.128.157.247) ---- Manual Page -- https://php.net/manual/en/function.array-filter.php Edit -- https://main.php.net/note/edit/126402 Del: integrated -- https://main.php.net/note/delete/126402/integrated Del: useless -- https://main.php.net/note/delete/126402/useless Del: bad code -- https://main.php.net/note/delete/126402/bad+code Del: spam -- https://main.php.net/note/delete/126402/spam Del: non-english -- https://main.php.net/note/delete/126402/non-english Del: in docs -- https://main.php.net/note/delete/126402/in+docs Del: other reasons-- https://main.php.net/note/delete/126402 Reject -- https://main.php.net/note/reject/126402 Search -- https://main.php.net/manage/user-notes.php

« previous php.notes (#216931) next »