Saturday, September 15, 2012

Elance PHP5 Code Test Answer


Here is the list of problems with correct answers for Elance PHP5 Code Test:
1. recursive xml traversal:
01function 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}
2. (sql) select the second highest id from user table:
1SELECT id FROM user ORDER BY id DESC LIMIT 1,1
3. get checkbox values from POST:
1$res array();
2while(list($checkbox,) = each($_POST))
3{
4    $res[] = intval(substr($checkbox,strpos($checkbox,'_') + 1));
5}
6sort($res);
7echo implode(' ',$res);
4. get unique array elements:
1function GetUniqueOnes($arr)
2{
3    $res = implode(',',array_unique($arr));
4
5    return $res;
6}
5. generate random password:
01function 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}
6. split email addresses:
1function SplitEmailAddress($address)
2{
3    list($user$domain) = explode('@',$address);
4    return array('user' => $user'domain' => $domain);
5}
7. the most challenging task (for me). Phone regexps:
1function 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}
8. get longest string in arguments:
01function 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}
9. find maximum in nested array:
1function 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}
10. output all numbers divisable by 8 from 200 to 600 inclusive:
1for($i = 200; $i <= 592; $i+=8)
2{
3    echo $i.',';
4}
5echo $i;
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

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.