Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- /*
- * Demonstration of how to flatten an array of arbitrarily nested arrays.
- * No error checking is done here. This assumes that the test array ($myarray) is properly formed.
- */
- echo 'hello<br>';
- // Some test data
- $myarray = array( 1,
- 2,
- 3.4,
- 4,
- 'mikey',
- array( 4,
- 5,
- array( 99,
- 88)
- ),
- 6
- );
- // Something to hold the results
- $result = Array();
- // let's get started
- echo 'Initial array:<br>';
- print_r($myarray);
- flatten($myarray, $result);
- echo '<br><br>Result array:<br>';
- print_r($result);
- /*
- * Flattens an array of arbitrarily-nested arrays.
- * While the instruction stated integer-only values would be used, this function flattens arrays regardless of their content.
- *
- * Parameters:
- * $input - the value to be checked/flattened
- * $result - passed by reference, a place to hold the results.
- */
- function flatten($input, &$result) {
- if(gettype($input) == 'array')
- {
- // if the input is an array, continue to flatten
- foreach($input as $key=>$value){
- flatten($value, $result);
- }
- } else {
- // Assign value to result array
- $result[] = $input;
- }
- // nothing to return
- }
- ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement