note 106480 deleted from function.array-unique by crell

From: Date: Tue, 12 Apr 2022 00:50:04 +0000
Subject: note 106480 deleted from function.array-unique by crell
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-218165@lists.php.net to get a copy of this message
Note Submitter: gma (at) qoob (dot) gr ---- Lets say that you want to capture unique values from multidimensional arrays and flatten them in 0 depth. i.e. <?php $tmp = array( 'a' => array( 1,2,3,4 ), 'b' => array( 'c' => array( 4,5,6,7 ) ) ); ?> will return with array_flat( $tmp ) --> array( 1,2,3,4,5,6,7 ); I hope that the function will help someone <?php /** * @params : $a array the recursion array * : $s array storage array * : $l integer the depth level * */ if( !function_exists( 'array_flat' ) ) { function array_flat( $a, $s = array( ), $l = 0 ) { # check if this is an array if( !is_array( $a ) ) return $s; # go through the array values foreach( $a as $k => $v ) { # check if the contained values are arrays if( !is_array( $v ) ) { # store the value $s[ ] = $v; # move to the next node continue; } # increment depth level $l++; # replace the content of stored values $s = array_flat( $v, $s, $l ); # decrement depth level $l--; } # get only unique values if( $l == 0 ) $s = array_values( array_unique( $s ) ); # return stored values return $s; } # end of function array_flat( ... } ?>

« previous php.notes (#218165) next »