PHP Array Functions

Questions

33

Last updated

Mar 10, 2024

PHP array functions are regular among the very important ones that interviewers select for candidates. For those who are unaware of PHP array, this is a data structure that allows developers to store multiple elements with similar data type under a single variable, which save developers the effort to create a different variable for every data. The PHP arrays functions are extremely helpful creating a list of elements of similar types, which developers will able to access using their key or index.

Types of arrays in PHP;
  • Numeric or Indexed Arrays,
  • Multidimensional Arrays
  • Associative Arrays

Most Frequently Asked PHP Arrays

Here in this article, we will be listing frequently asked PHP Arrays and Answers with the belief that they will be helpful for you to gain higher marks. Also, to let you know that this article has been written under the guidance of industry professionals and covered all the current competencies.

Q1. How many types of array supported in php?
Answer

PHP supports three types of arrays:-

  • Indexed Array
  • Associative array
  • Multi-dimensional Array
Q2. How to use array_pop() and array_push() in PHP?
Answer

1. array_pop()

It is used to delete or remove the last element of an array.

Example

$a=array("blue","black","skyblue");
array_pop($a);

OUTPUT : Array ( [0] => blue[1] => black)

2. array_push()

It is used to Insert one or more elements to the end of an array.

Example

$a=array("apple","banana"); array_push($a,"mango","pineapple");

OUTPUT : Array ( [0] => apple[1] => banana[2] => mango[3] => pineapple)

Also Read: PHP Strings
Q3. How to use array_merge() and array_combine() in PHP?
Answer
array_combine()

array_combine() : It is used to create a new array by using the key of one array as keys and using the value of another array as values. The most important thing is using array_combine() that, number of values in both arrays should be same.

$name = array("best","interview","question");
$index = array("1","2","3");
$result = array_combine($name,$index);

array_merge()

array_merge() : It merges one or more than one array such that the value of one array appended at the end of first array and if the arrays have same strings key then the later value overrides the previous value for that key .

$name = array("best","interview","question");
$index = array("1","2","3");
$result = array_merge($name,$index);

Q4. How to get total number of elements used in array?
Answer

We can use the count() or sizeof() function to get the number of elements in an array.

$array1 = array("1","4","3");
echo count($array1);

OUTPUT : 3

Q5. How to insert an new array element in array?
Answer

$originalArray = array( 'ram', 'sita', 'luxman', 'hanuman', 'ravan' );
$newArray = array( 'kansh' );
array_splice( $originalArray, 3, 0, $newArray);

// OUTPUT is ram sita luxman hanuman kansh ravan

Q6. How to get specific key value from array in php?
Answer

To check key in the array, we can use array_key_exists().

$item=array("name"=>"umesh","class"=>"mca");
if (array_key_exists("name",$item))
{
   echo "Key is exists";
}
else
{
   echo "Key does not exist!";
}

 

 

Q7. What is the use of is_array() and in_array()?
Answer

is_array() : It is an inbuilt function used in PHP. It is used to check whether a variable is an array or not.

in_array() : It is used to check whether a given value exists in an array or not. It returns TRUE if the value is exists in array, and returns FALSE otherwise.

Q8. Explain different sorting function in PHP?
Answer
  • sort() - It is used to sort an array in ascending order
  • rsort() - It is used to sort an array in descending order
  • asort() - It is used to sort an associative array in ascending order, according to the value
  • ksort() - It is used to sort an associative array in ascending order, according to the key
  • arsort() - It is used to sort an associative array in descending order, according to the value
  • krsort() - It is used to sort an associative array in descending order, according to the key
Q9. What is implode() in php?
Answer
PHP implode() function is used join array elements with a string.In other words we can say it returns a string from the elements of an array.

$array = array('My','Name','Is','BestInterViewQuestion');
echo implode(" ",$array)


// OUTPUT : My Name Is BestInterViewQuestion

Q10. What is explode() in php?
Answer

PHP explode() function is used to break a string into an array.

$string = "My Name Is BestInterviewQuestion";
print_r (explode(" ",$string));

// OUTPUT : Array ( [0] => My [1] => Name [2] => Is [3] => BestInterviewQuestion )

Q11. What is the use of array_search() in php?
Answer

array_search() is a inbuilt function of PHP which is used to search a particular value in an array and if the value is found then it returns its corresponding its key.

$array = array("1"=>"My", "2"=>"Name", "3"=>"is", "4"=>"BestInterviewQuestion");
echo array_search("BestInterviewQuestion",$array);

// OUTPUT 4

Q12. How to get elements in reverse order of an array in php?
Answer

For this we can use array_reverse() function.

$array = array("1"=>"Best","2"=>"Interview","3"=>"Question");
print_r(array_reverse($array));

// OUTPUT Array ( [3] => Question [2] => Interview[1] => Best)

Q13. How do you remove duplicates from an array?
Answer

We can use the PHP array_unique() function to remove the duplicate vlaues form an array.

$array = array("a"=>"best","b"=>"interviewquestion","c"=>"best");
print_r(array_unique($array));

// OUTPUT : Array ( [a] => best [b] => interviewquestion)

Q14. What is the different between count() and sizeof() in php?
Answer

Both are used to count elements in a array.sizeof() function is an alias of count() function used in PHP. count() function is faster and butter than sizeof().

$array = array('1','2','3','4');
$size = count($array);

//OUTPUT : 4

Q15. How to check a variable is array or not in php?
Answer

We can check a variable with the help of is_array() function in PHP. It's return true if variable is an array and return false otherwise.

$var = array('X','Y','Z');
if (is_array($var))
echo 'It is an array.';
else
echo 'It is not an array.';

 

Q16. What is the use of array_count_values() in php?
Answer

It is an inbuilt function in PHP. It is one of the most simple functions that is used to count all the values inside an array. In other words we can say that it is used to calculate the frequency of all of the elements of an array.

$array = array("B","Cat","Dog","B","Dog","Dog","Cat");
print_r(array_count_values($array));

// OUTPUT : Array ( [B] => 2 [Cat] => 2 [Dog] => 3 )

Q17. What are the difference between array_keys() and array_key_exists() in php?
Answer

array_key_exists() : It is used to checks an array for a particular key and returns TRUE if the key exists and FALSE if the key does not exist.

array_keys() : This function returns an array containing the keys. It takes three parameters out of which one is mandatory and other two are optional.
Syntax : array_keys(array,value,strict)

Q18. What is the difference between array_merge() and array_merge_recursive() in php?
Answer
array_merge() array_merge_recursive()
This function is used to join one or more arrays into a single array. Used to merge multiple arrays in such a manner that values of one array are appended to the end of the previous array.
Syntax: array_merge($array1, $array2, $array3...); Syntax: array_merge_recursive($array1, $array2, $array3...);
If we pass a single array, it will return re-indexed as a numeric array whose index starts from zero. If we pass a single array, it will return re-indexed in a continuous manner.
Example of an array_merge() function:

$arrayFirst = array("Topics" => "Maths","Science", "Computers");
$arraySecond = array("Class-V", "Class-VI", "Section"=>"C");
$resultArray = array_merge($arrayFirst, $arraySecond);
print_r($resultArray);

Output

Array ( [Topics] => Maths [0] => Science [1] => Computers [2] => Class-V [3] => Class-VI [Section] => C )

Example of an array_merge_recursive() function with all different keys:

$a1=array("a"=>"Best", "b"=>"Interview");
$a2=array("z"=>"Question");
print_r(array_merge_recursive($a1, $a2));

Output

: Array
(
[a] => Best
[b] => Interview
[z] => Question
)

Q19. Write a PHP script to get the largest key in an array?
Answer

You can use rsort() to get the highest value in the array.

$array = array('5','2','8','4');
$result = rsort($array);


//OUTPUT : 8

Q20. What is array filter in PHP?
Answer

The array_filter() method filters the values of an array the usage of a callback function. This method passes each value of the input array to the callback function. If this callback function returns true then the current value from the input is returned into the result array.

Syntax:

array_filter(array, callbackfunction, flag)

  • array(Required)
  • callbackfunction(Optional)
  • flag(Optional)

function test_odd_number(int $var)
{
   return($var & 1);
}
$array=array(1,3,2,3,4,5,6);
print_r(array_filter($array,"test_odd_number"));

Q21. What is the difference between associative array and indexed array?
Answer
Associative Arrays Indexed or Numeric Arrays
This is a type of arrays which used named specific keys to assign and store values in the database. This type of arrays store and assign values in a numeric fashion with count starting from zero.
Example of an associative array:

$name_two["i am"] = "zara";
$name_two["anthony is"] = "Hello";
$name_two["ram is"] = "Ananya";
echo "Accessing elements directly:\n";

echo $name_two["i am"], "\n";
echo $name_two["anthony is"], "\n";
echo $name_one["Ram is"], "\n";

Output:

Accessing elements directly:
zara
Hello
Ananya

Example of an indexed or numeric array:

$name_two[1] = "Sonu Singh";
echo "Accessing the array elements directly:\n";
echo $name_two[1], "\n";

Output:

Sonu Singh

Q22. Which array function checks if the particular key exists in the array?
Answer

In PHP arrays, the array_key_exists() function is used when the user wants to check if a specific key is present inside an array. If the function returns with a TRUE value, it is present.

Here’s its syntax: array_key_exists(array_key, array_name)

Also, here is an example of how it works

$array1 = array("Orange" => 100, "Apple" => 200, "Grapes" => 300, "Cherry" => 400);
if (array_key_exists("Grapes",$array1))
{
echo "Key exists";
}
else
{
echo "Key does not exist";
}

Output:

key exists

Q23. What is associative array in PHP?
Answer

Associative arrays are used to store key and value pairs. For example, to save the marks of the unique subjects of a scholar in an array, a numerically listed array would no longer be a nice choice.

/* Method 1 */
$student = array("key1"=>95, "key2"=>90, "key3"=>93);

/* Method 2 */
$student["key1"] = 95;
$student["key2"] = 90;
$student["key3"] = 93

Q24. How to get single value from array in php?
Answer

In PHP, if you want to access a single value from an array, be it a numeric, indexed, multidimensional or associative array, you need to use the array index or key.
Here’s an example using a multidimensional array:

$superheroes = array(
array(
"name" => "Name",
"character" => "BestInterviewQuestion",
),
array(
"name" => "Class",
"character" => "MCA",
),
array(
"name" => "ROLL",
"character" => "32",
)
);
echo $superheroes[1]["name"];

 

Output:

CLASS

Q25. How to add key and value in array in php?
Answer

In PHP, pushing a value inside an array automatically creates a numeric key for itself. When you are adding a value-key pair, you actually already have the key, so, pushing a key again does not make sense. You only need to set the value of the key inside the array. Here’s an example to correctly push a [air pf value and key inside an array:

$data = array(
   "name" => "Best Interview Questions"
);

array_push($data['name'], 'Best Interview Questions');

Now, here to push “cat” as a key with “wagon” as the value inside the array $data, you need to do this:

$data['name']='Best Interview Questions';

Q26. How to get first element of array in php?
Answer

There are various methods in PHP to get the first element of an array. Some of the techniques are the use of reset function, array_slice function, array_reverse, array_values, foreach loop, etc.

Suppose we have an array like
$arrayVar = array('best', 'interview', 'question', 'com');

1. With direct accessing the 0th index:
echo $arrayVar[0];

2. With the help of reset()
echo reset($arrayVar);

3. With the help of foreach loop
foreach($arrayVar as $val) {
    echo $val;
    break; // exit from loop
}

Q27. How to change array index in PHP?
Answer

$array = array('1' => 'best', '2' => 'interview', '3' => 'question')
$array[3] = $array[5];
unset($array[3]);

// OUTPUT
array('1' => 'best', '2' => 'interview', '5' => 'question')

Q28. How to get common values from two array in php?
Answer

To select the common data from two arrays in PHP, you need to use the array_intersect() function. It compares the value of two given arrays, matches them and returns with the common values. Here’s an example:

$a1=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow");
$a2=array("e"=>"red","f"=>"black","g"=>"purple");
$a3=array("a"=>"red","b"=>"black","h"=>"yellow");

$result=array_intersect($a1,$a2,$a3); print_r($result);

Output:

Array ( [a] => red )

Q29. How to get array key value in php?
Answer

The array_keys() function is used in PHP to return with an array containing keys.
Here is the syntax for the array_keys() function: array_keys(array, value, strict)

Here is an example to demonstrate its use

$a=array("Volvo"=>"AAAAAAAA","BMW"=>"BBBBBBB","Toyota"=>"CCCCCC");
print_r(array_keys($a));

Output:

Array ( [0] => Volvo [1] => BMW [2] => Toyota )

Q30. How to print array values in php?
Answer

To print all the values inside an array in PHP, use the for each loop.

Here’s an example to demonstrate it:

$colors = array("Red", "Green", "Blue", "Yellow", "Orange");

// Loop through colors array foreach($colors as $value){ echo $value . "
"; }

Output:

Red
Green
Blue
Yellow
Orange

Q31. How to store fetch data in array in php?
Answer
Q32. How to get second last element of array in php?
Answer

The count() function is assuming that the indexes of your array go in order; by way of the usage of stop and prev to go the array pointer, you get the genuine values. Try the use of the count() method on the array above and it will fail.

$array = array(5,6,70,10,36,2);
echo $array[count($array) -2];

// OUTPUT : 36

Q33. How to display array structure and values in PHP?
Answer

You can either use the PHP var_dump() or print_r() function to check the structure and values of an array. The var_dump() method gives more information than print_r().

$lists = array("Best", "Interview", "Questions");
// Print the array
print_r($lists);
var_dump($lists);