Here is the list of problems with correct answers for Elance PHP5 Code Test:
1. recursive xml traversal:
01 | function ReadXml( $xmlstr ) |
04 | $xml = new SimpleXMLElement( $xmlstr ); |
06 | if ( count ( $xml ->children())) |
08 | $res .= $xml ->getName().PHP_EOL; |
09 | foreach ( $xml ->children() as $child ) |
11 | ReadXml( $child ->asXML()); |
16 | $res .= $xml ->getName(). ': ' .(string) $xml .PHP_EOL; |
2. (sql) select the second highest id from user table:
1 | SELECT id FROM user ORDER BY id DESC LIMIT 1,1 |
3. get checkbox values from POST:
2 | while (list( $checkbox ,) = each( $_POST )) |
4 | $res [] = intval ( substr ( $checkbox , strpos ( $checkbox , '_' ) + 1)); |
4. get unique array elements:
1 | function GetUniqueOnes( $arr ) |
3 | $res = implode( ',' , array_unique ( $arr )); |
5. generate random password:
01 | function GeneratePassword ( $length , $chars ) |
04 | $char_length = strlen ( $chars ); |
05 | for ( $i = 0; $i < $length ; $i ++) |
07 | $res .= $chars [rand(0, $char_length )]; |
6. split email addresses:
1 | function SplitEmailAddress( $address ) |
3 | list( $user , $domain ) = explode ( '@' , $address ); |
4 | return array ( 'user' => $user , 'domain' => $domain ); |
7. the most challenging task (for me). Phone regexps:
1 | function ReformatPhoneNumber( $number ) |
3 | if (preg_match( '/^(\d[ -]?){7,12}$/' , $number , $matches )) |
5 | return preg_replace( '/[ -]/' , '' , $number ); |
8 | throw new Exception( 'Invalid phone number' ); |
8. get longest string in arguments:
01 | function GetLongestString() |
04 | foreach (func_get_args() as $arg ) |
9. find maximum in nested array:
4 | array_walk_recursive ( $arr ,create_function( '$item,$key' , 'if($item > $GLOBALS["max"]) $GLOBALS["max"] = $item;' )); |
5 | return $GLOBALS [ 'max' ]; |
10. output all numbers divisable by 8 from 200 to 600 inclusive:
1 | for ( $i = 200; $i <= 592; $i +=8) |
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