Interview

10 PHP Array Interview Questions and Answers

Prepare for your PHP interview with our guide on PHP arrays. Enhance your understanding and problem-solving skills with curated questions and answers.

PHP arrays are a fundamental aspect of PHP programming, offering a versatile way to store and manipulate data. Arrays in PHP can hold multiple values under a single name, and they come in various types such as indexed, associative, and multidimensional arrays. This flexibility makes them indispensable for tasks ranging from simple data storage to complex data manipulation and retrieval operations.

This article aims to prepare you for technical interviews by providing a curated selection of PHP array-related questions and answers. By familiarizing yourself with these examples, you will gain a deeper understanding of array operations and enhance your problem-solving skills, making you more confident and proficient in handling PHP array challenges during interviews.

PHP Array Interview Questions and Answers

1. Create an associative array with keys “name”, “age”, and “city” and corresponding values “John”, 25, and “New York”. Print the value associated with the key “city”.

To create an associative array in PHP with keys “name”, “age”, and “city” and corresponding values “John”, 25, and “New York”, use the following code:

<?php
$person = array(
    "name" => "John",
    "age" => 25,
    "city" => "New York"
);

echo $person["city"];
?>

2. Given an array of integers, write a PHP function to sort the array in descending order.

To sort an array of integers in descending order in PHP, use the rsort() function. This function modifies the original array.

Example:

function sortDescending($array) {
    rsort($array);
    return $array;
}

$numbers = array(3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5);
$sortedNumbers = sortDescending($numbers);

print_r($sortedNumbers);

3. Write a PHP function to check if a specific value exists in an array and return its index if found.

To check if a specific value exists in an array and return its index, use the array_search function in PHP. It returns the key if successful, or false if not found.

Example:

function findValueIndex($array, $value) {
    $index = array_search($value, $array);
    return $index !== false ? $index : -1;
}

$array = array("apple", "banana", "cherry");
$value = "banana";
echo findValueIndex($array, $value); // Output: 1

4. Given an array of integers, write a PHP function to filter out all even numbers.

To filter out even numbers from an array of integers in PHP, use array_filter with a callback function. This function iterates over each element and applies the callback to determine inclusion.

Example:

function filterEvenNumbers($array) {
    return array_filter($array, function($num) {
        return $num % 2 !== 0;
    });
}

$inputArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
$resultArray = filterEvenNumbers($inputArray);

print_r($resultArray);

5. Write a PHP function that takes an array of strings and returns a new array with all strings converted to uppercase.

To convert all strings in an array to uppercase in PHP, use array_map with strtoupper. This applies a callback to each element.

Example:

function convertToUppercase($array) {
    return array_map('strtoupper', $array);
}

$input = ['hello', 'world', 'php', 'arrays'];
$output = convertToUppercase($input);

print_r($output);
// Output: Array ( [0] => HELLO [1] => WORLD [2] => PHP [3] => ARRAYS )

6. Implement a PHP function that reduces an array of numbers to their sum.

To reduce an array of numbers to their sum, use the array_sum function. It takes an array and returns the sum of its elements.

Example:

function sumArray($numbers) {
    return array_sum($numbers);
}

// Example usage
$numbers = [1, 2, 3, 4, 5];
echo sumArray($numbers); // Outputs: 15

7. Implement a PHP class that uses arrays to represent a stack data structure with push, pop, and peek methods.

A stack is a linear data structure that follows the Last In, First Out (LIFO) principle. In PHP, arrays can implement a stack using built-in functions to add and remove elements.

Example:

class Stack {
    private $stack;

    public function __construct() {
        $this->stack = array();
    }

    public function push($element) {
        array_push($this->stack, $element);
    }

    public function pop() {
        if (!$this->isEmpty()) {
            return array_pop($this->stack);
        }
        return null;
    }

    public function peek() {
        if (!$this->isEmpty()) {
            return end($this->stack);
        }
        return null;
    }

    public function isEmpty() {
        return empty($this->stack);
    }
}

// Example usage:
$stack = new Stack();
$stack->push(1);
$stack->push(2);
echo $stack->peek(); // Outputs: 2
echo $stack->pop();  // Outputs: 2
echo $stack->pop();  // Outputs: 1

8. Write a PHP function to apply a given callback function to each element of an array (array mapping).

Array mapping in PHP involves applying a callback function to each element. Use array_map for this purpose.

Example:

function applyCallbackToArray($array, $callback) {
    return array_map($callback, $array);
}

$array = [1, 2, 3, 4, 5];
$callback = function($element) {
    return $element * 2;
};

$result = applyCallbackToArray($array, $callback);
print_r($result); // Output: [2, 4, 6, 8, 10]

9. Write a PHP function to split an array into chunks of a specified size.

To split an array into chunks of a specified size, use array_chunk. It returns a multidimensional array with sub-arrays of the specified size.

Example:

function splitArrayIntoChunks($array, $chunkSize) {
    return array_chunk($array, $chunkSize);
}

$array = [1, 2, 3, 4, 5, 6, 7, 8, 9];
$chunkSize = 3;
$result = splitArrayIntoChunks($array, $chunkSize);

print_r($result);

10. Write a PHP function to flip the keys and values of an associative array.

To flip the keys and values of an associative array, use array_flip(). It swaps keys and values.

Example:

function flipArray($array) {
    return array_flip($array);
}

$originalArray = array("a" => 1, "b" => 2, "c" => 3);
$flippedArray = flipArray($originalArray);

print_r($flippedArray);

In this example, array_flip() swaps the keys and values of $originalArray, resulting in $flippedArray with values as keys and keys as values.

Previous

10 Semantic HTML Interview Questions and Answers

Back to Interview
Next

15 Computer Hardware Interview Questions and Answers