Skip to content

Instantly share code, notes, and snippets.

@dontfight
Last active August 15, 2017 15:32
Show Gist options
  • Select an option

  • Save dontfight/30abac6e5ddca70dc3c4bf1e02fa4d65 to your computer and use it in GitHub Desktop.

Select an option

Save dontfight/30abac6e5ddca70dc3c4bf1e02fa4d65 to your computer and use it in GitHub Desktop.
Code Challenge
<?php
/*
*
*
Write a function in PHP, named printList, that takes 2 parameters (only!): a string, and a nested array.
The function will generate a string with the value of each element on a separate line.
The value will be preceded by the string and also indicate the position and index within the array.
ie.
$list = array("stringA", array("a", "b", "c"), "stringB", array("stringC"));
with a call like printList("Foo", $list) would result in:
Foo[0] = stringA
Foo[1][0] = a
Foo[1][1] = b
Foo[1][2] = c
Foo[2] = stringB
Foo[3][0] = stringC
*/
/**
*
* The function will generate a string with the value of each element on a separate line.
*
* @param string $outputBase
* @param array $input
*/
function printList(string $outputBase, array $input)
{
foreach ($input as $key => $value) {
$output = "{$outputBase}[{$key}]";
if (is_array($value) && count($value)) {
// handle array recursively
print printList("{$output}", $value);
} else if (is_array($value) && count($value) == 0) {
// handle empty array value
print "{$output} = " . PHP_EOL;
} else {
// handle non-array value
print "{$output} = $value" . PHP_EOL;
}
}
}
printList("Foo00", array( null, [], "stringA", array("a", "b", "c", array(1, 2, 3)), "stringB", array("stringC")));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment