note 127216 added to function.array-filter

From: Date: Sun, 03 Jul 2022 20:51:15 +0000
Subject: note 127216 added to function.array-filter
Groups: php.notes 
Request: Send a blank email to php-notes+get-218892@lists.php.net to get a copy of this message
Check if all elements in array are not empty/null/falsy. ------------------------------ Supposing you have a one dimensional array... <?php $spicy_numbers = [69, 420, ɸ]; ?> And you want to easily check that all elements in said array are not null/empty/any falsy value, instead of running a loop over each element, you can pass the array to <?php array_filter() ?>, with no callback function, and then check if the returned array is the same size as the original, since <?php array_filter() ?> strips out all non-truthy values including 0 when no callback is provided. Example: <?php $spicy_numbers = [69, 420, '']; // Phi is gone! if ( count( array_filter( $spicy_numbers ) ) !== count( $spicy_numbers ) ) { // One of the elements is empty/null/falsy. } else { // All elements present and truthy. } ?> As a neat little function, you could do this: <?php /** * Checks if all of given array's elements have a non-falsy value. * Use-case: If all items in array are set and have a value (truthy, of course), then do X; else, do Y. * * @param array $arr * @return bool */ function is_array_full( $arr ) { $array_count = count( $arr ); $filtered_count = count( array_filter( $arr ) ); return ( $array_count === $filtered_count ) ? true : false; } ?> ---- Server IP: 45.112.84.4 Probable Submitter: 45.91.157.133 (proxied: 73.243.12.79) ---- Manual Page -- https://php.net/manual/en/function.array-filter.php Edit -- https://main.php.net/note/edit/127216 Del: integrated -- https://main.php.net/note/delete/127216/integrated Del: useless -- https://main.php.net/note/delete/127216/useless Del: bad code -- https://main.php.net/note/delete/127216/bad+code Del: spam -- https://main.php.net/note/delete/127216/spam Del: non-english -- https://main.php.net/note/delete/127216/non-english Del: in docs -- https://main.php.net/note/delete/127216/in+docs Del: other reasons-- https://main.php.net/note/delete/127216 Reject -- https://main.php.net/note/reject/127216 Search -- https://main.php.net/manage/user-notes.php

« previous php.notes (#218892) next »