PHP Arrays


Arrays in PHP are a fundamental data structure used to store multiple values in a single variable. Arrays allow you to manage large sets of data efficiently, whether indexed, associative, or multidimensional. This article covers frequently asked interview questions and answers on arrays in PHP.


What is an array in PHP?

Answer:
An array in PHP is a special variable that can hold multiple values at once. Arrays allow you to group related data together in one place. You can access each element by its index or key.

Example of a simple array:

$colors = ["red", "green", "blue"];

What are the different types of arrays in PHP?

Answer:
PHP supports three types of arrays:

  • Indexed array: An array with a numeric index.
  • Associative array: An array where each element is associated with a key.
  • Multidimensional array: An array containing one or more arrays.

How do you create an indexed array in PHP?

Answer:
An indexed array is created by simply listing values, with numeric indexes assigned automatically, starting from 0.

$fruits = ["apple", "banana", "cherry"];
echo $fruits[0]; // Outputs: apple

What is an associative array, and how do you create one in PHP?

Answer:
An associative array is an array where each key has a specific value. Instead of numeric indexes, you use named keys.

$person = ["name" => "John", "age" => 30, "city" => "New York"];
echo $person["name"]; // Outputs: John

How do you create a multidimensional array in PHP?

Answer:
A multidimensional array is an array that contains other arrays as its elements. You can create one by nesting arrays.

$matrix = [
   [1, 2, 3],
   [4, 5, 6],
   [7, 8, 9]
];
echo $matrix[1][2]; // Outputs: 6

How do you loop through an array in PHP?

Answer:
You can loop through an array using various loops like foreach, for, or while. The foreach loop is most commonly used for arrays.

$colors = ["red", "green", "blue"];
foreach ($colors as $color) {
   echo $color . " "; // Outputs: red green blue
}

How do you add elements to an array in PHP?

Answer:
You can add elements to an array by specifying the index or using an empty pair of square brackets to append the element at the end of the array.

$colors = ["red", "green"];
$colors[] = "blue"; // Appends "blue" to the array

For associative arrays:

$person["gender"] = "male"; // Adds "gender" => "male" to the array

What is the array_push() function used for?

Answer:
The array_push() function adds one or more elements to the end of an array. It is useful when you want to add multiple values at once.

$colors = ["red", "green"];
array_push($colors, "blue", "yellow");
print_r($colors); // Output: Array ( [0] => red [1] => green [2] => blue [3] => yellow )

How do you remove an element from an array in PHP?

Answer:
To remove an element from an array, you can use the unset() function. This will remove the specified element by its index or key.

$fruits = ["apple", "banana", "cherry"];
unset($fruits[1]); // Removes "banana"
print_r($fruits); // Output: Array ( [0] => apple [2] => cherry )

How do you count the number of elements in an array in PHP?

Answer:
You can count the number of elements in an array using the count() function.

$fruits = ["apple", "banana", "cherry"];
echo count($fruits); // Outputs: 3

How do you check if a value exists in an array in PHP?

Answer:
The in_array() function checks if a value exists in an array and returns true if found, otherwise it returns false.

$fruits = ["apple", "banana", "cherry"];
echo in_array("banana", $fruits); // Outputs: 1 (true)

How do you check if a key exists in an array in PHP?

Answer:
You can check if a specific key exists in an array using the array_key_exists() function.

$person = ["name" => "John", "age" => 30];
echo array_key_exists("name", $person); // Outputs: 1 (true)

What is the difference between array_merge() and array_combine() in PHP?

Answer:

  • array_merge(): Combines two or more arrays by merging them into one array.
  • array_combine(): Creates an associative array using one array for keys and another array for values.

Example of array_merge():

$array1 = ["red", "green"];
$array2 = ["blue", "yellow"];
$result = array_merge($array1, $array2);

Example of array_combine():

$keys = ["name", "age"];
$values = ["John", 30];
$result = array_combine($keys, $values);

How do you sort an array in PHP?

Answer:
PHP provides several functions for sorting arrays:

  • sort(): Sorts an indexed array in ascending order.
  • rsort(): Sorts an indexed array in descending order.
  • asort(): Sorts an associative array by values, maintaining key-value pairs.
  • ksort(): Sorts an associative array by keys.

Example of sort():

$numbers = [4, 2, 8, 1];
sort($numbers);
print_r($numbers); // Output: Array ( [0] => 1 [1] => 2 [2] => 4 [3] => 8 )

What is the difference between array_diff() and array_intersect()?

Answer:

  • array_diff(): Compares two or more arrays and returns the elements that are present in the first array but not in the others.
  • array_intersect(): Compares two or more arrays and returns the elements that are present in all arrays.

Example of array_diff():

$array1 = ["red", "green", "blue"];
$array2 = ["green", "yellow"];
$result = array_diff($array1, $array2);
print_r($result); // Output: Array ( [0] => red [2] => blue )

Example of array_intersect():

$array1 = ["red", "green", "blue"];
$array2 = ["green", "yellow"];
$result = array_intersect($array1, $array2);
print_r($result); // Output: Array ( [1] => green )

How do you get all the keys of an array in PHP?

Answer:
You can get all the keys of an array using the array_keys() function.

$person = ["name" => "John", "age" => 30];
$keys = array_keys($person);
print_r($keys); // Output: Array ( [0] => name [1] => age )

How do you get all the values of an array in PHP?

Answer:
You can get all the values of an array using the array_values() function.

$person = ["name" => "John", "age" => 30];
$values = array_values($person);
print_r($values); // Output: Array ( [0] => John [1] => 30 )

What is the array_map() function in PHP?

Answer:
The array_map() function applies a callback function to each element of an array and returns the modified array.

function double($n) {
   return $n * 2;
}
$numbers = [1, 2, 3];
$doubled = array_map("double", $numbers);
print_r($doubled); // Output: Array ( [0] => 2 [1] => 4 [2] => 6 )

How does the array_filter() function work in PHP?

Answer:
The array_filter() function filters elements of an array using a callback function. Only elements that pass the filter (i.e., return true) are included in the resulting array.

$numbers = [1, 2, 3, 4, 5];
$evenNumbers = array_filter($numbers, function($n) {
   return $n % 2 == 0;
});
print_r($evenNumbers); // Output: Array ( [1] => 2 [3] => 4 )

What is the array_reduce() function in PHP?

Answer:
The array_reduce() function iteratively reduces an array to a single value using a callback function. It is useful for operations like summing values.

function sum($carry, $item) {
   return $carry + $item;
}
$numbers = [1, 2, 3, 4];
$total = array_reduce($numbers, "sum");
echo $total; // Output: 10
Ads