20 PHP array logical interview questions and answers - Mostlikers

20 PHP array logical interview questions and answers

Greetings Readers! This article delves into advanced PHP logical interview questions, a crucial aspect of technical assessments. Interviewers often present intricate PHP logical problems, and here, we've compiled some challenging questions to sharpen your problem-solving skills. Feel free to explore, and if you have additional questions, share them in the comments for further discussion.




Question 1: Sort an Array Without Using Any Sorting Function in PHP

a) Example $array = array(1, 6, 23, 10, 3, 2, 15,7); make this array ascending order without any inbuilt function.

Answer :
<?php 
    $array = array(1, 6, 23, 10, 3, 2, 15,7);
    $total = count($array);
    for ($i=0; $i < $total; $i++) { 
        for ($j=$i+1; $j < $total; $j++) { 
            if($array[$i] > $array[$j]) {
                $temp = $array[$i];
                $array[$i] = $array[$j];
                $array[$j] = $temp;
            }
        }
    }
    echo '<pre>';
    echo "Ascending Sorted Array is: "; 
    print_r($array);
?>

OUTPUT
Before sorted Array is: Array
(
    [0] => 1
    [1] => 6
    [2] => 23
    [3] => 10
    [4] => 3
    [5] => 2
    [6] => 15
    [7] => 7
)
Ascending Sorted Array is: Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 6
    [4] => 7
    [5] => 10
    [6] => 15
    [7] => 23
)

b) Example $array = array(1, 6, 23, 10, 3, 2, 15,7); make this array in descending order without any inbuilt function.

<?php 
    $array = array(1, 6, 23, 10, 3, 2, 15,7);
    $total = count($array);
    for ($i=0; $i < $total; $i++) { 
        for ($j=$i+1; $j < $total; $j++) { 
            if($array[$i] < $array[$j]) {
                $temp = $array[$i];
                $array[$i] = $array[$j];
                $array[$j] = $temp;
            }
        }
    }
    echo '<pre>';
    echo "Descending Sorted Array is: "; 
    print_r($array);
?>

OUTPUT
Ascending Sorted Array is: Array
(
    [0] => 23
    [1] => 15
    [2] => 10
    [3] => 7
    [4] => 6
    [5] => 3
    [6] => 2
    [7] => 1
)

If you want to arrange strings in ascending order using a PHP string-building function, simply use sort(). For descending order, you can use rsort().
<?php 
    $array = array(1, 6, 23, 10, 3, 2, 15,7);
    $array2 = array(1, 6, 23, 10, 3, 2, 15,7);
    sort($array); // asending order
    rsort($array2); // descending order
    echo '<pre>'; print_r($array);
    echo '<pre>'; print_r($array2);
?>


Question 2: Find the smallest and largest number in an array without using any function.

 a) Find the minimum array value $array = array(2,7,10,25,35,65,80);
<?php
    $array = array(2,7,10,25,35,65,80);
    $count = count($array);
    $min = $array[0];
    for ($i=0; $i < $count; $i++) { 
        if($array[$i] < $min)
        {
            $min = $array[$i];
        }
    }
    echo "minmum value $min";
    //output 2
?>

b) Find the maximum array value $array = array(2,7,10,25,35,65,80);
<?php
    $array = array(2,7,10,25,35,65,80);
    $count = count($array);
    $max = $array[0];
    for ($i=0; $i < $count; $i++) { 
        if($array[$i] > $max)
        {
            $max = $array[$i];
        }
    }
    echo "maximum value $max";
    //output 80
?>

Effortlessly Find Minimum and Maximum Array Values in PHP with min() and max() Functions.
<?php
    $array = array(2,7,10,25,35,65,80);
    $min = min($array);
    $max = max($array);
    //php function
?>


Question 3: Write a program to make a chessboard

<table width="300" cellspacing="0" cellpadding="0" border="1">  
<?php
for ($rows=1; $rows < 8 ; $rows++) { 
    echo '<tr>';
    for ($colum=1; $colum < 8; $colum++) { 
        $total = $rows + $colum;
        if($total % 2 ==0)
        {
            echo "<td width='40' height='40' bgcolor='#FFFFF'></td>";
        }
        else
        {
            echo "<td width='40' height='40' bgcolor='#00000'></td>";
        }
    }
    echo '</tr>';
 } 
?>
</table> 

Chessboard OUTPUT


Question 4 : How to Locate an Email Address in a Given Text Without Prior Information? Explore Solutions Using Regular Expressions and Alternative Methods?


example 
$body = "This is a sentence and it has to find find@me.com in it"; 

Answer: by using Regular expressions
$body = "This is a sentence and it has to find find@me.com in it"; 
echo $str = preg_replace('/([a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6})/', '<a href="mailto:$1">$1</a>', $body);

Answer: Alternative methods

<?php
$body = "This is a sentence and it has to find find@me.com in it"; 
$email_find = explode(' ',$body);
foreach ($email_find as $key => $email) {
    if(filter_var($email, FILTER_VALIDATE_EMAIL)) {
        echo $email.'<br/>';
    }
}
?>


Question 5:   What approach would you use in PHP to discover and list prime numbers within the range from 1 to 100?


Answer 

<?php
$number = 2;
while ($number < 100) 
{
    $divid_number=0;
    for ($i=1;$i<=$number;$i++) 
    { 
        if (($number%$i)==0) 
        {
            $divid_number++;
        }
    }
    if ($divid_number < 3) 
    {
        echo $number.'<br>';
    }
    $number = $number+1;
}
?>

OUTPUT
2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,

Question 6: In PHP, explain a method to remove duplicates from an array without utilizing any built-in functions. Provide a sample code demonstrating your approach.

Answer

<?php
    $number = array(1, 3, 4, 2, 1, 6, 4, 9, 7, 2, 9);
    $newArr = array();
    foreach($number as $val){
       $newArr[$val] = $val;
    }
    echo '<pre>'; print_r($newArr);
?>

OUTPUT

Old Array
(
    [0] => 1
    [1] => 4
    [2] => 2
    [3] => 1
    [4] => 6
    [5] => 4
    [6] => 9
    [7] => 7
    [8] => 2
    [9] => 9
)
New Array
(
    [0] => 1
    [1] => 4
    [2] => 2
    [3] => 6
    [4] => 9
    [5] => 7
)

Using PHP's built-in function to remove duplicate elements from an array:
<?php
    $number = array_unique(array(1, 3, 4, 2, 1, 6, 4, 9, 7, 2, 9));
    echo '<pre>'; print_r($number);
?>
In this PHP code snippet, the array_unique function is employed to eliminate duplicate elements from the array, resulting in a unique set of values.


Question 7: In PHP, demonstrate how to display only the duplicate values from an array without utilizing any built-in functions. For example, given the array $arr = array(8, 9, 10, 3, 4, 8, 7, 9, 11, 3), provide a code snippet that outputs only the duplicate values.


Answer :
<?php
$arr = array(8,9,10,3,4,8,7,9,11,3);
foreach($arr as $key => $val)
{
  unset($arr[$key]); 
  if (in_array($val,$arr))
  {
    echo $val . ",";
  }
} // ouput 8,9,3
?>

Question 8. Write a Function that combines two lists by alternatingly taking elements. For example, Given two lists [a, b, c] and [1, 2, 3] the function should return [a, 1, b, 2, c, 3]


  Answer

<?php
    $arr = array(1,2,3);
    $arr1 = array(a,b,c);
    $new_array = array();

    for ($i=0; $i < count($arr); $i++)
    { 
        $new_array[] = $arr[$i];
        $new_array[] = $arr1[$i];

    }
    echo '<pre>'; print_r($new_array);
?>

OUTPUT

Array
(
    [0] => 1
    [1] => a
    [2] => 2
    [3] => b
    [4] => 3
    [5] => c
)

Question 9. How can you obtain the highest and second-highest values from an array using a single line of code in PHP?

Answer

      $array = [10, 5, 8, 12, 7];
      rsort($array);
      list($highest, $secondHighest) = $array;
      echo "Highest: $highest, Second Highest: $secondHighest";
       
      //Output : Highest: 12, Second Highest: 10

Question 10. How can you reverse the text in PHP? Provide an example using the text "I love my country." Include both solutions: one using built-in functions and another without using built-in functions.

Answer Using Built-in Functions:
 $text = "I love my country";
 $reversedText = strrev($text);
 echo "Reversed Text (with built-in function): $reversedText";
 //Output : yrtnuoc ym evol I

Answer Without Using Built-in Functions:

$text = "I love my country";
$reversedText = strrev($text);
echo "Reversed Text (with built-in function): $reversedText";
//Output : yrtnuoc ym evol I
  

Question 11. Write a PHP function to calculate the factorial of a given number using recursion. 

Answer

function calculateFactorial($number) {
    if ($number <= 1) {
        return 1;
    } else {
        return $number * calculateFactorial($number - 1);
    }
}
 
// Example usage
$number = 5;
$factorial = calculateFactorial($number);
echo "The factorial of $number is: $factorial";
 
//Output : The factorial of 5 is: 120

Question 12. Write a PHP function to find the maximum occurring element in an array. Provide an example using the array [3, 2, 4, 2, 2, 4, 1].


Answer
function findMaxOccurrence($arr) {
    $count = array_count_values($arr);
    $maxValue = max($count);
    $maxOccurrence = array_search($maxValue, $count);
    return $maxOccurrence;
}
 
// Example usage
$array = [3, 2, 4, 2, 2, 4, 1];
$result = findMaxOccurrence($array);
echo "The element with the maximum occurrence is: $result";
 
 
//Output : The element with the maximum occurrence is: 2

Question 13. Write a PHP program to generate the following pattern?


*
* *
* * *
* * * *
* * * * *

Answer
<?php
$rows = 5;
 
for ($i = 1; $i <= $rows; $i++) {
    for ($j = 1; $j <= $i; $j++) {
        echo "* ";
    }
    echo "<br>";
}
?>

8 comments:

  1. I am new in PHP can You explain it please. Please dry run this code.

    ReplyDelete
  2. 1.Sort an array without using any sorting function in PHP
    Please explain it-

    $array = array(1, 6, 23, 10, 3, 2, 15,7);
    $total = count($array);
    for ($i=0; $i < $total; $i++) {
    for ($j=$i+1; $j < $total; $j++) {
    if($array[$i] > $array[$j]) {
    $temp = $array[$i];
    $array[$i] = $array[$j];
    $array[$j] = $temp;
    }
    }
    }
    echo "Ascending Sorted Array is: ";
    print_r($array);

    ReplyDelete
    Replies
    1. $array[$j]) {
      Check array first value greater than second value
      $temp = $array[$i]; if condition true make that value to $temp value
      $array[$i] = $array[$j]; assign first array value to second array value
      $array[$j] = $temp; second value assign to temp value
      }
      }
      }

      if the value greate than it will swipe to first value
      echo "Ascending Sorted Array is: ";
      print_r($array);

      ?>

      Delete
  3. how to get highest and second highest from single line code

    $highest = $array[count($array)-1];

    or

    $second_highest = $array[count($array)-2];

    ReplyDelete
  4. Rahulya.coding31 July 2022 at 04:32

    $arr = array(1, 6, 23, 10, 3, 2, 15,7);
    sort($arr);
    $second_highest = $arr[sizeof($arr)-2];
    echo $second_highest;

    ReplyDelete
  5. Rahulya.coding31 July 2022 at 04:32

    $arr = array(1, 6, 23, 10, 3, 2, 15,7);
    sort($arr);
    $second_highest = $arr[sizeof($arr)-2];
    echo $second_highest;

    ReplyDelete
  6. This comment has been removed by a blog administrator.

    ReplyDelete