Showing posts with label interview questions. Show all posts
Showing posts with label interview questions. Show all posts

Find the second Highest value in array.



$array = array('200', '15','69','122','50','201');
$max_1 = $max_2 = 0;

for($i=0; $i{
    if($array[$i] > $max_1)
    {
      $max_2 = $max_1;
      $max_1 = $array[$i];
    }
    else if($array[$i] > $max_2)
    {
      $max_2 = $array[$i];
    }
}
echo "Max=".$max_1;
echo "
";
echo "Smax 2=".$max_2;

?>

Reference :

max — Find highest value

echo max(2, 3, 1, 6, 7);  // 7
echo max(array(2, 4, 5)); // 5

min() - Find lowest value

count() - Count all elements in an array, or something in an object

Golden Rules of programming


1 . The AND operator is used when we use (=) and the operator OR is used when we use (!=)
2. True ( || )     False ( && )

Comments urs.

What will be the output of the PHP code snippet below?



==========================
$v = 1;
$m = 2;
$l = 3;

if( $l > $m > $v){
    echo "yes";
}else{
    echo "no";
}
=========================

Ans:

Since 3 > 2 > 1, one might be fooled into thinking the output would be “yes”.

In fact, though, the output will be “no”.

Here’s why:


First, $l > $m will be evaluated which yields a boolean value of 1 or true. Comparing that boolean value to the integer value 1 (i.e., bool(1) > $v) will result in NULL, so the output will be “no”.

How would you sort an array of strings to their natural case-insensitive order, while maintaing their original index association?

For example, the following array:

array(
                '0' => 'z1',
                '1' => 'Z10',
                '2' => 'z12',
                '3' => 'Z2',
                '4' => 'z3',
)
After sorting, should become:

array(
                '0' => 'z1',
                '3' => 'Z2',
                '4' => 'z3',
                '1' => 'Z10',
                '2' => 'z12',
)

The trick to solving this problem is to use three special flags with the standard asort() library function:

asort($arr, SORT_STRING|SORT_FLAG_CASE|SORT_NATURAL)

The function asort() is a variant of the standard function sort() that preserves the index association. The three flags used above SORT_STRING, SORT_FLAG_CASE and SORT_NATURAL forces the sort function to treat the items as strings, sort in a case-insensitive way and maintain natural order respectively.

Note: Using the natcasesort() function would not be a correct answer, since it would not maintain the original index association of the elements of the array.