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();
|
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
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’;
?>
|
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]);
?>
|
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 ”
“; }?>
|
1
2
3
4
|
$array=array(1,2,3,4,5,6,7,8);
echo sizeof($array);
?>
|
Out of the above code will be the size of array. It will be 8.
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.
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));
?>
?>
|
Pass an associative array in function array_keys() and this will return an array of keys.
- 2Shares
2 thoughts on “PHP array Interview Question and Answers”