Elance PHP5 code test (with answers)

Here is the list of problems with correct answers for Elance PHP5 Code Test:

1. recursive xml traversal:

 
function ReadXml($xmlstr)
{
    static $res = '';
    $xml = new SimpleXMLElement($xmlstr);
 
    if(count($xml->children()))
    {
        $res .= $xml->getName().PHP_EOL;
        foreach($xml->children() as $child)
        {
            ReadXml($child->asXML());
        }
    }
    else
    {
        $res .= $xml->getName().': '.(string)$xml.PHP_EOL;
    }
 
    return $res;
}

2. (sql) select the second highest id from user table:

SELECT id FROM user ORDER BY id DESC LIMIT 1,1

3. get checkbox values from POST:

    $res = array();
    while(list($checkbox,) = each($_POST))
    {
        $res[] = intval(substr($checkbox,strpos($checkbox,'_') + 1));
    }
    sort($res);
    echo implode(' ',$res);

4. get unique array elements:

 
function GetUniqueOnes($arr)
{
    $res = implode(',',array_unique($arr));
 
    return $res;
}

5. generate random password:

 
function GeneratePassword ($length,$chars)
{
    $res = '';
    $char_length = strlen($chars);
    for($i = 0; $i < $length; $i++)
    {
        $res .= $chars[rand(0,$char_length)];
    }
 
    return $res;
}

6. split email addresses:

function SplitEmailAddress($address)
{
    list($user, $domain) = explode('@',$address);
    return array('user' => $user, 'domain' => $domain);
}

7. the most challenging task (for me). Phone regexps:

function ReformatPhoneNumber($number)
{
    if (preg_match('/^(\d[ -]?){7,12}$/', $number, $matches))
    {
        return preg_replace('/[ -]/', '', $number);
    }
 
    throw new Exception('Invalid phone number');
}

8. get longest string in arguments:

function GetLongestString()
{
    $length = 0;
    foreach(func_get_args() as $arg)
    {
 
        $var = strlen($arg);
        if($var > $length)
        {
            $length = $var;
        }
    }
    return $length;
}

9. find maximum in nested array:

function MaxArray($arr)
{
    $GLOBALS['max'] = 0;
    array_walk_recursive($arr,create_function('$item,$key','if($item > $GLOBALS["max"]) $GLOBALS["max"] = $item;'));
    return $GLOBALS['max'];
}

10. output all numbers divisable by 8 from 200 to 600 inclusive:

for($i = 200; $i <= 592; $i+=8)
{
    echo $i.',';
}
echo $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:)

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert.

This site uses Akismet to reduce spam. Learn how your comment data is processed.