Tags:

PHP array Interview question-answers

By Dhananjay yadav January 13, 2018
What is an array?
An array is a collection of data in a sequential manner. In PHP an array may hold many types of data.

How to define an empty array in PHP?
There are many ways to define arrays in PHP
1
2
$cars=[];
$cars=array();
How to check that a variable is an array in PHP?
There is library method to check, whether a variable is an array or not.
is_array($variable); – the function accepts a variable as a parameter and returns Boolean. If variable passed in it is an array it returns TRUE.

How to check the size of array?
We can find the size of an array using sizeof() function.

How many types of arrays are there in PHP we use?
Usually, there are three types of arrays in PHP:
1- Indexed Array
2- Associative array
3- Multidimensional Array
How can we add new value into an array in rum time?
We can do this using php method array_push(). There is another way we can simply assign new value to array and it will hold the next index. For example
1
2
3
4
5
$car=array('BMW','Benz');
$car[]='Toyota';
$car[]='Sujuki';
?>
And finalil it will print: BMW,Benz,Toyota,Sujuki.
How can we remove a value from an array in PHP?
We can remove a value from an array in php using unset() method. We have to unset the index of that value.Suppose we have to delete ‘BMW’ from above array, then we have to unset the index of ‘BMW’ and tht is 0, so It will be as :
1
2
3
unset($car[0]);
?>
Demostrate foreach loop on a PHP array.
We are assuming that we have to print the name of cars in list using foreach loop. So we can do this as given in code snippet:
1
2
3
4
5
foreach($car as $key=>$value){
    echo "This a brand new ".$value;
    echo "
"
;
}?>
What will be the output when we execute the PHP code given below?
1
2
3
4
$array=array(1,2,3,4,5,6,7,8);
echo sizeof($array);
?>
OUTPUT:
Out of the above code will be the size of array. It will be 8.
How to sort an associative array in ascending order, according to the value?
We can use PHP library function asort(). This will sort the array in ascending order. In descending order, we will use arsort(). These functions return sorted arrays.
What is the function that we can use to remove the duplicate valuse from array in PHP?
PHP has array_unique() function to remove the duplicate values from array.
1
2
3
4
5
6
$fruits=array("a"=>"mangow","b"=>"orange","c"=>"apple","d"=>"mangow");
print_r(array_unique($fruits));
?>
?>
We aill get a list of uniq values.
How we can find an array of keys of another associative array?
Pass an associative array in function array_keys() and this will return an array of keys.

Post Tags:

No Comment to " PHP array Interview question-answers "