Here is the list of problems with correct answers for Elance PHP5 Code Test:
1. recursive xml traversal:
2. (sql) select the second highest id from user table:
3. get checkbox values from POST:
4. get unique array elements:
5. generate random password:
6. split email addresses:
7. the most challenging task (for me). Phone regexps:
8. get longest string in arguments:
9. find maximum in nested array:
10. output all numbers divisable by 8 from 200 to 600 inclusive:
Note, that all answers are correct, but some of them are not
optimized, so you may be in top 20% with this, but not higher. If
someone would like to post any improvements to the code snippets above -
they are welcome:)
1. recursive xml traversal:
01 | function ReadXml($xmlstr) |
02 | { |
03 | static $res = ''; |
04 | $xml = new SimpleXMLElement($xmlstr); |
05 |
06 | if(count($xml->children())) |
07 | { |
08 | $res .= $xml->getName().PHP_EOL; |
09 | foreach($xml->children() as $child) |
10 | { |
11 | ReadXml($child->asXML()); |
12 | } |
13 | } |
14 | else |
15 | { |
16 | $res .= $xml->getName().': '.(string)$xml.PHP_EOL; |
17 | } |
18 |
19 | return $res; |
20 | } |
1 | SELECT id FROM user ORDER BY id DESC LIMIT 1,1 |
1 | $res = array(); |
2 | while(list($checkbox,) = each($_POST)) |
3 | { |
4 | $res[] = intval(substr($checkbox,strpos($checkbox,'_') + 1)); |
5 | } |
6 | sort($res); |
7 | echo implode(' ',$res); |
1 | function GetUniqueOnes($arr) |
2 | { |
3 | $res = implode(',',array_unique($arr)); |
4 |
5 | return $res; |
6 | } |
01 | function GeneratePassword ($length,$chars) |
02 | { |
03 | $res = ''; |
04 | $char_length = strlen($chars); |
05 | for($i = 0; $i < $length; $i++) |
06 | { |
07 | $res .= $chars[rand(0,$char_length)]; |
08 | } |
09 |
10 | return $res; |
11 | } |
1 | function SplitEmailAddress($address) |
2 | { |
3 | list($user, $domain) = explode('@',$address); |
4 | return array('user' => $user, 'domain' => $domain); |
5 | } |
1 | function ReformatPhoneNumber($number) |
2 | { |
3 | if (preg_match('/^(\d[ -]?){7,12}$/', $number, $matches)) |
4 | { |
5 | return preg_replace('/[ -]/', '', $number); |
6 | } |
7 |
8 | throw new Exception('Invalid phone number'); |
9 | } |
01 | function GetLongestString() |
02 | { |
03 | $length = 0; |
04 | foreach(func_get_args() as $arg) |
05 | { |
06 |
07 | $var = strlen($arg); |
08 | if($var > $length) |
09 | { |
10 | $length = $var; |
11 | } |
12 | } |
13 | return $length; |
14 | } |
1 | function MaxArray($arr) |
2 | { |
3 | $GLOBALS['max'] = 0; |
4 | array_walk_recursive($arr,create_function('$item,$key','if($item > $GLOBALS["max"]) $GLOBALS["max"] = $item;')); |
5 | return $GLOBALS['max']; |
6 | } |
1 | for($i = 200; $i <= 592; $i+=8) |
2 | { |
3 | echo $i.','; |
4 | } |
5 | echo $i; |
These list are ch-alleging even for teachers.
ReplyDelete