PHP Array Interview Questions & Answers

Top PHP Array Interview Questions & Answers list

Here, you can read about PHP Array related Interview Questions & Answers. This list contains popular & frequently asked interview questions related to PHP Arrays functions. Prepare for Jobs using our PHP FAQs list.

What are the different PHP functions to sort an array?

PHP has many functions to sort an array. Choose one by asking: do you sort by value or by key, in which order, and do you need to keep the keys?

FunctionSortsKeeps keys?
sort()Values, low to highNo
rsort()Values, high to lowNo
asort()Values, low to highYes
arsort()Values, high to lowYes
ksort()Keys, low to highYes
krsort()Keys, high to lowYes
usort()Values using your own functionNo
uasort() / uksort()Values / keys using your own functionYes

For text with numbers like “img2” and “img10”, natsort() gives a natural order. Here is a custom sort with usort().

<?php
$people = [["Anil", 30], ["Robin", 25], ["Zoya", 22]];

usort($people, fn($a, $b) => $a[1] <=> $b[1]);   // by age

echo $people[0][0];
?>

Output:

Tutorials Class - Output Window

Zoya

See more examples in PHP Array Functions and ksort().

PHP’s numerically indexed array begins with which position?

A numerically indexed array in PHP begins with position 0, not 1. The first element has the key 0, the second has 1, and so on.

<?php
$array = [15, 80, 67, 33];

echo $array[0] . "<br>";
echo $array[3];
?>

Output:

Tutorials Class - Output Window

15
33

This array has 4 elements, so the keys are 0, 1, 2 and 3. If you try $array[4], PHP shows a warning “Undefined array key 4”, because there is no element at that position. The last key is always count($array) - 1.

Which PHP function inserts an element to the end of an array?

Use array_push() to add one or more elements to the end of an array. A shorter way for one element is $array[] = value.

<?php
$fruits = ["Apple", "Banana"];

array_push($fruits, "Mango", "Orange");
$fruits[] = "Grapes";

print_r($fruits);
?>

Output:

Tutorials Class - Output Window

Array
(
[0] => Apple
[1] => Banana
[2] => Mango
[3] => Orange
[4] => Grapes
)

To add an element at the start use array_unshift(). To remove the last or the first element use array_pop() and array_shift(). See PHP Array Functions.

How many types of arrays are available in PHP?

There are three types of arrays in PHP.

TypeKeysExample
Indexed arrayNumbers, from 0["Apple", "Banana"]
Associative arrayNames that you choose["name" => "Robin", "age" => 25]
Multidimensional arrayAn array inside an array[[1, 2], [3, 4]]
<?php
$indexed = ["Apple", "Banana"];
$assoc = ["name" => "Robin", "age" => 25];
$multi = [[1, 2], [3, 4]];

echo $indexed[1] . "<br>";
echo $assoc["name"] . "<br>";
echo $multi[1][0];
?>

Output:

Tutorials Class - Output Window

Banana
Robin
3

Learn all of them with examples in PHP Arrays.

What is the use of array_chunk() function in PHP?

array_chunk() splits an array into smaller arrays (chunks) of the size that you give. The syntax is array_chunk(array, size, preserve_keys).

<?php
$numbers = [1, 2, 3, 4, 5];

echo json_encode(array_chunk($numbers, 2)) . "<br>";

$data = ["a" => 1, "b" => 2, "c" => 3];
echo json_encode(array_chunk($data, 2, true));
?>

Output:

Tutorials Class - Output Window

[[1,2],[3,4],[5]]
[{“a”:1,”b”:2},{“c”:3}]

The last chunk can be smaller. By default the keys are not kept, pass true as the third parameter to keep them. It is useful to show items in rows or to process a big array in parts.

What is the use of in_array() function in PHP?

in_array() checks if a value exists in an array. It returns true if the value is found, and false if not.

<?php
$fruits = ["Apple", "Banana", "Cherry"];

var_dump(in_array("Banana", $fruits));
var_dump(in_array("Mango", $fruits));

// Third parameter true = check the data type also
var_dump(in_array("1", [1, 2, 3]));
var_dump(in_array("1", [1, 2, 3], true));
?>

Output:

Tutorials Class - Output Window

bool(true)
bool(false)
bool(true)
bool(false)

By default in_array() compares loosely, so the string “1” matches the number 1. Pass true as the third parameter for a strict comparison. To get the position of the value, use array_search(), and to check a key use array_key_exists().

Which PHP function counts all the values of an array?

array_count_values() counts how many times each value appears in an array. It returns a new array where the values become keys and the counts become values.

<?php
$fruits = ["apple", "banana", "apple", "orange", "apple"];

print_r(array_count_values($fruits));
?>

Output:

Tutorials Class - Output Window

Array
(
[apple] => 3
[banana] => 1
[orange] => 1
)

It works only with strings and integers. If you only need the total number of elements, use count().

How do you split a string into an array?

Use explode() to split a string into an array at a separator, like a comma. Here the extra spaces after the commas are removed with trim().

<?php
$languages = "PHP, HTML, CSS, JavaScript, MySQL";

$list = array_map("trim", explode(",", $languages));

print_r($list);
?>

Output:

Tutorials Class - Output Window

Array
(
[0] => PHP
[1] => HTML
[2] => CSS
[3] => JavaScript
[4] => MySQL
)

To split a string into single characters use str_split(). To split by a pattern (like many spaces) use preg_split().

<?php
echo json_encode(str_split("PHP")) . "<br>";
echo json_encode(preg_split("/\s+/", "one   two three"));
?>

Output:

Tutorials Class - Output Window

[“P”,”H”,”P”]
[“one”,”two”,”three”]

Learn more in PHP explode() Function.

What is the use of ksort() in PHP?

ksort() sorts an array by its keys in ascending order (A to Z, 1 to 9). It keeps the key and value pairs together. To sort the keys in reverse order use krsort().

<?php
$age = ["Robin" => 25, "Anil" => 30, "Zoya" => 22];

ksort($age);
print_r($age);
?>

Output:

Tutorials Class - Output Window

Array
(
[Anil] => 30
[Robin] => 25
[Zoya] => 22
)

<?php
$age = ["Robin" => 25, "Anil" => 30, "Zoya" => 22];

krsort($age);
print_r($age);
?>

Output:

Tutorials Class - Output Window

Array
(
[Zoya] => 22
[Robin] => 25
[Anil] => 30
)

Both functions sort the original array (they do not return a new one). To sort by value use asort() and arsort().

How to merge two or more arrays in PHP?

Use the array_merge() function to merge two or more arrays into one new array. You can also use the + operator, but it works in a different way.

<?php
$a = [1, 2];
$b = [3, 4];
$c = [5, 6];

print_r(array_merge($a, $b, $c));
?>

Output:

Tutorials Class - Output Window

Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
[5] => 6
)

array_merge() vs + operator. When two arrays have the same string key, array_merge() keeps the later value, but the + operator keeps the first value.

<?php
$x = ["a" => "Apple", "b" => "Banana"];
$y = ["b" => "Blueberry", "c" => "Cherry"];

print_r(array_merge($x, $y));
print_r($x + $y);
?>

Output:

Tutorials Class - Output Window

Array
(
[a] => Apple
[b] => Blueberry
[c] => Cherry
)
Array
(
[a] => Apple
[b] => Banana
[c] => Cherry
)

For numeric keys, array_merge() renumbers the keys from 0, while + keeps the keys and skips the ones that already exist. From PHP 7.4 you can also merge with the spread operator, like [...$a, ...$b].

How to count the elements of a multidimensional array in PHP?

The count() function counts only the first level of an array. To count all elements including the inner arrays, pass COUNT_RECURSIVE as the second parameter.

<?php
$cars = [
    ["Volvo", 22, 18],
    ["BMW", 15, 13]
];

echo count($cars) . "<br>";
echo count($cars, COUNT_RECURSIVE);
?>

Output:

Tutorials Class - Output Window

2
8

The first line counts the 2 inner arrays. The recursive count adds 6 inner values to them, so it is 8. The function sizeof() is only an alias of count().

How to convert an array to a string in PHP?

Use the implode() function to join the values of an array into a string. If you need the complete array with keys, use json_encode().

<?php
$numbers = [1, 2, 5, 12];

echo implode(",", $numbers);
?>

Output:

Tutorials Class - Output Window

1,2,5,12

<?php
$user = ["name" => "Robin", "age" => 25];

echo json_encode($user);
?>

Output:

Tutorials Class - Output Window

{“name”:”Robin”,”age”:25}

Note: If you try echo $array directly, PHP prints the word “Array” and gives a warning “Array to string conversion”. Use one of the functions above instead.

Read more about implode() in PHP implode() Function. To do the opposite, see PHP explode() Function.

How to remove duplicate values from an array in PHP?

Use the array_unique() function. It removes the duplicate values and keeps only the first one. The keys of the remaining values are not changed.

<?php
$fruits = ["a" => "apple", "b" => "banana", "c" => "apple"];

print_r(array_unique($fruits));
?>

Output:

Tutorials Class - Output Window

Array
(
[a] => apple
[b] => banana
)

For a normal numeric array, you will see gaps in the keys after removing duplicates. Use array_values() to reindex it from 0.

<?php
$numbers = [1, 2, 2, 3, 1];

print_r(array_values(array_unique($numbers)));
?>

Output:

Tutorials Class - Output Window

Array
(
[0] => 1
[1] => 2
[2] => 3
)

By default array_unique() compares values as strings, so "1" and 1 are treated as same value.

How to get keys and values separately from an associative array in PHP?

Use array_keys() to get all the keys and array_values() to get all the values of an associative array. Both return a new array.

<?php
$data = ["key1" => "value1", "key2" => "value2", "key3" => "value3"];

print_r(array_keys($data));
print_r(array_values($data));
?>

Output:

Tutorials Class - Output Window

Array
(
[0] => key1
[1] => key2
[2] => key3
)
Array
(
[0] => value1
[1] => value2
[2] => value3
)

If you need both together, use a foreach loop with the key and value.

<?php
$data = ["key1" => "value1", "key2" => "value2", "key3" => "value3"];

foreach ($data as $key => $value) {
    echo $key . " = " . $value . "<br>";
}
?>

Output:

Tutorials Class - Output Window

key1 = value1
key2 = value2
key3 = value3

How to move the internal pointer of an array in PHP?

Every PHP array has an internal pointer that points to one element. You can move it with these functions:

FunctionWhat it does
current()Returns the element where the pointer is now
key()Returns the key of the current element
next()Moves the pointer one step forward
prev()Moves the pointer one step back
reset()Moves the pointer to the first element
end()Moves the pointer to the last element
<?php
$fruits = ["apple", "banana", "cherry"];

echo current($fruits) . "<br>";
echo next($fruits) . "<br>";
echo next($fruits) . "<br>";
echo prev($fruits) . "<br>";
echo reset($fruits) . "<br>";
echo end($fruits);
?>

Output:

Tutorials Class - Output Window

apple
banana
cherry
banana
apple
cherry

When the pointer goes outside the array, next() and prev() return false.