Your Ad Here

Saturday, July 14, 2012

Elance PHP5 code test solutions

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;
 


No comments:

Post a Comment