PHP

List of 20 Array functions in PHP with example

What is Array?

The array is a collection of items. The array is used for data types. The array is a special type of data structure that stores fixed-size data collection. We can store any amount of data in the array and use it easily. It also works like a database in which we can store the data. You can store it and use it. The array is a collection in which a lot of data can be stored. Array removes the complexity of the data. Many data problems can be removed by using PHP Array. The array() function is used to create an array. PHP array() function can contain (store, collect) many values.

Syntax:-

array("value1", "value2 ", "value3");

Example 1:-

<?php
       $fruits = array("Banana", "Mango ", "Orange");
       echo "I like " . $fruits[0] . ", " . $fruits[1] . " and " . $fruits[2] . ".";
?>

Output:-

1. array_merge() function

The “array_merge” function provides the easiest way to merge a list of arrays. It can take as many parameters as you give to it and it will merge all of them into a single one and return back to you.

Example:-

<?php
    $myarray1 = array(1,2,3);
    $myarray2 = array(4,5,6);
    $myarray3 = array(7,8,9);
    $single_merged_array = array_merge($myarray1,$myarray2,$myarray3);
    print_r($single_merged_array);

?>

Output:-

2. Sorting Arrays In PHP:

There are two ways to sort elements of an array. If you want a simple default ascending order sorting with non-object array elements, then you can go for the “sort” function. You just pass the array as a parameter and it will sort the array and returns true if successful.

Example:-

<?php
    $simple_array = array("dbc","bcd","abc");
    if(sort($simple_array)){
        echo "<pre>";
      print_r($simple_array);
      echo "</pre>";
    }
?>

Output:-

3. array_diff() function

If you are trying to exclude a few elements from an array that is common to another array’s elements, then “array_diff” is the perfect function for you.

Example:-

<?php
    $myarray1 = array(1,2,3,4,-1,-2);
    $myarray2 = array(-1,-2);
    $filtered_array = array_diff($myarray1,$myarray2);

    echo "<pre>";
    print_r($filtered_array);
    echo "</pre>";
?>

Output:-

4. array_intersect() function

If you are trying to get only the common elements from two different arrays, “array_intersect” is the proper function for such a purpose.

Example:-

<?php
   $myarray1 = array(1,2,3,4,-1,-2);
   $myarray2 = array(-1,-2,3);
   $common_array = array_intersect($myarray1,$myarray2);

   echo "<pre>";
   print_r($common_array);
   echo "</pre>";
?>

Output:-

5. array_keys() function

If you somehow need to get either only the keys or values of an associative array, you can do so with help of “array_keys” or “array_values” functions. 

Example:-

<?php
    $my_array = array("key1"=>"value 1","key2"=>"value 2","key3"=>"value 3");
    
    echo "<pre>";
    print_r(array_keys($my_array));
    echo "<br>";
    print_r(array_values($my_array));
    echo "</pre>";
   
?>

Output:-

6. array_unique() function

“array_unique” – another angel function to me :D. It will remove duplicate entries and make the array contains only distinct elements. Just pass the array as its parameter and we are done! If you are trying to make unique elements that are of object type, then make sure to implement your own _toString() function inside the class and return a string value that represents the identity of the object and it should do the work fine.

Example:-

<?php
    $a=array("a"=>"red","b"=>"green","c"=>"red");

    echo "<pre>";
    print_r(array_unique($a));
    echo "</pre>";
 
?>

Output:-

7. empty array in PHP

When an empty array and then start entering elements in it later. With the help of this, it can prevent different errors due to a faulty array. It helps to have the information of using bugged, rather than having the array. It saves time during debugging. Most of the time it may not have anything to add to the array at the point of creation.

Syntax

$emptyArray = []; 
$emptyArray = array();
$emptyArray = (array) null;

Example:-

<?php 
   // Declare an empty array 
   $empty_array = array();
      
   // Function to count array 
   // element and use condition
   if(count($empty_array) == 0)
       echo "Array is empty";
   else
       echo "Array is non- empty";
?>

Output:-

8.unset() Function

The built-in function unset() is used to delete the value stored in a variable. It is only applicable to the local variables. It does not reflect its behavior on global variables. We can use this function to delete an element from an array.

unset($variableName);

Example:-

<?php
   //Declare the array
   $nicname = array("Vijay","Amit","Rahul","Dharmendra","Roshan");

   unset($nicname[2]);

   echo "<pre>";
   echo "The array is:\n";
   print_r($nicname);
   echo "</pre>";
?>

Output:

9. array_splice() Function

The function array_splice() is used to add elements to an array or delete elements from an array.

Example:-

<?php
    //Declare the array
    $nicname = array("Vijay","Amit","Dharmu","Roshan","Dilip","Rahul","Dhyanchand","Shohan");

    array_splice($nicname, 4, 3);
    echo "<pre>";
    echo "The array is:\n";
    print_r($nicname);
    echo "</pre>";
?>

Output:-

10. array_diff() Function

The built-in function array_diff() finds the difference between two or more arrays. It can be used to delete multiple values from an array without affecting their indexes.

Sy

array_diff($array1, $array2, $array3, ... , $arrayN);

It takes N number of arrays as the parameters. It compares the first array with all other arrays and returns an array that contains all the elements of the first array that are not present in other arrays.

Example

<?php
    //Declare the array
    $nicname = array("Vijay","Amit","Dharmu","Roshan","Rahul","Devanand","Ramayan","Dillyan");

    $nicname = array_diff($nicname, array("Vijay","Amit"));
    echo "<pre>";
    echo "The array is:\n";
    print_r($nicname);
    echo "</pre>";
?>

Output:-

11. array_combine() function

The array_combine() function is used to combine two arrays and create a new array by using one array for keys and another array for values i.e. all elements of one array will be the keys of the new array and all elements of the second array will be the values of this new array.

Syntax:

array_combine(array1, array2)

Example:-

<?php
   // Define array1 with keys 
   $array1 = array("subject1" ,"subject2");
  
   // Define array2 with  values
   $array2 = array( "Vijay", "Ram");
  
   // Combine two arrays
   $final = array_combine($array1, $array2);
  
   // Display merged array
   echo "<pre>";
   print_r($final);
   echo "</pre>";
?>

Output:-

12. array_key_exists() function

The PHP array_key_exists() function checks if a specific key exists in the array. The function returns TRUE if the key is present, else it returns FALSE. array_key_exists() function works for both indexed arrays and associative arrays. For indexed arrays, an index is a key.

Syntax

array_key_exists( key, array)

Example:-

<?php
    $array1 = array("a"=>"apple", "b"=>"banana", "m"=>"mango", "o"=>"orange");
    $key = "m";
    if (array_key_exists($key, $array1)) {
       echo "Key exists in the array!";
    } else {
       echo "Key does not exist in the array!";
    }
?>

Output:-

13.  json_encode() function

To convert the PHP array to JSON, use the json_encode() function. The json_encode() is a built-in PHP function that converts an array to JSON. The json_encode() function returns the string containing a JSON equivalent of the value passed to it, as demonstrated by the numerically indexed array. We can also convert any JSON received from a server into JavaScript objects.

Example:-

<?php

    $netflix = ['Black Mirror', '13 Reasons Why', 'Bird Box', 'Dirt'];

    $netJSON = json_encode($netflix);

    echo $netJSON."\n";
    
?>

Output:-

14. count()function 

The count() method is used to calculate all the elements in the array or any other countable object. It can be used for both uni-dimensional as well as multi-dimensional arrays. 

syntax:-

count(array)

Example

<?php
        $parts = array(

                "Ram" => array(
                "SSD",
                "Processor"
            ),
                "Key" => array(
                "Monitor"  
            ),
                "Mouse" => array(
                "Cebal"
            )
        );
        
        echo "<pre>";
        print_r($parts);
        echo "</pre>";
        
        echo "Sub elements of an array: "
            . count($parts) . "<br>";
        echo "All elements of an array: "
            . count($parts, 1);
        
?>

Output:-

15. sizeof()

The sizeof() method is used to calculate all the elements present in an array or any other countable object. It can be used for both uni-dimensional as well as multi-dimensional arrays. 

syntax

sizeof(arr, mode)

example:-

<?php
    $parts = array(
        "Computer" => array(
        "SSD",
        "Processor"
    ),
        "Keyboard" => array(
        "Monitor"  
    ),
        "Mouse" => array(
        "CPU"
    )
);
    echo "<pre>";
    print_r($parts);
    echo "</pre>";
    
    echo "Sub elements of an array: "
        . sizeof($parts) . "<br>";
    echo "All elements of an array: "
        . sizeof($parts, 1);
?>

Output:-

16. array_rand() function

The array_rand() function is used to get a random value from an array. This function accepts an array as a parameter and returns a random key from the array.

Syntax:-

array_rand($array, $number_of_items)

Example:-

<?php
    $my_arr = ["Vijay", "Amit", "Dharmu", "Rahul", "Ravi"];

    $rand_index = array_rand($my_arr);

    echo $my_arr[$rand_index];
?>

Output:-

17. shuffle() function

If you’re looking for a quick and easy way to get a random item from an array using PHP, the shuffle() function is the way to go. This function will randomly shuffle the items in an array, making it easy to get a random item.

Syntax:-

shuffle($arr)[0];

Example:-

<?php
    $my_arr = [
        "a" => 100,
        "b" => 200,
        "c" => 300,
        "4" => 400
    ];

    shuffle($my_arr);

    echo $my_arr[0];
?>

Output:-

18. array_push() function

PHP array_push() is a built-in function used to insert new elements at the end of an array and get the updated array elements. The array_push() method takes a single element or an array of elements and appends it to the array.

Syntax:-

array_push(array,value1,value2...)

Example:-

<?php
    $nicname = ["Vijay", "Amit", "Dharmu"];

    array_push($nicname, "Ravi", "Rahul");

    echo "<pre>";
    print_r($nicname);
    echo "</pre>";
?>

Output:-

19. array_pop() function

PHP array_pop() function to remove an element or value from the end of an array. The array_pop() function also returns the last value of an array. However, if the array is empty (or the variable is not an array), the returned value will be NULL.

Syntax:-

array_pop(array);

Example:-

<?php
    $nicname = ["Vijay", "Amit", "Dharmu", "rahul"];

    array_pop($nicname);

    echo "<pre>";
    print_r($nicname);
    echo "</pre>";
?>

Output:-

20. array_values()

The  array_values() is an inbuilt PHP function is used to get an array of values from another array that may contain key-value pairs or just values. The function creates another array where it stores all the values and by default assigns numerical keys to the values.

Syntax:

array array_values($array)

Example:-

<?php
    $array = [
        'phone'  => 'iPhone',
        'laptop' => 'Carbon X1',
        'car'    => 'Tesla',
    ];

    $values = array_values($array);

    echo "<pre>";
    print_r($values);
    echo "</pre>";

?>

Output:-

What is the difference between array PUSH and POP? explain with example

In PHP, the array methods like array_push and array_pop are used to add or remove elements or items from the array. The array_push method can use to add or insert one or more items or elements from the end of an array. and The array_pop() method can use to extract, delete and remove the elements/items from the end of the array.

array_push() function

PHP array_push() is a built-in function used to insert new elements at the end of an array and get the updated array elements. The array_push() method takes a single element or an array of elements and appends it to the array.

Syntax:-

array_push(array,value1,value2...)

Parameters

An array parameter is required to which we will add the value.

The value1 parameter is also required, which is the value we will insert into the specified array.

The value2, value3, and so on are optional parameters. However, we need to pass those parameters if we want to add multiple values.

Example:-

<?php
    $nicname = ["Vijay", "Amit", "Dharmu"];

    array_push($nicname, "Ravi", "Rahul");

    echo "<pre>";
    print_r($nicname);
    echo "</pre>";
?>

Output:-

array_pop() function

PHP array_pop() function to remove an element or value from the end of an array. The array_pop() function also returns the last value of an array. However, if the array is empty (or the variable is not an array), the returned value will be NULL.

Syntax:-

array_pop(array);

Example:-

<?php
    $nicname = ["Vijay", "Amit", "Dharmu", "rahul"];

    array_pop($nicname);

    echo "<pre>";
    print_r($nicname);
    echo "</pre>";
?>

Output:-

How to get a random value from a PHP array? explain with example

There are two types of getting a random value from a PHP array.

  • array_rand() function
  • shuffle() function

array_rand() function

When working with PHP, sometimes you need to get random values from an array. This can be easily accomplished with the array_rand() function. We will show in this post several methods that can be used to get random items from an array.

The array_rand() function is used to get a random value from an array. This function accepts an array as a parameter and returns a random key from the array.

Syntax:-

array_rand($array, $number_of_items)

Parameters

The array_rand() function takes two parameters. One is the array from which you want to get the random key.

$array: [Required] This is a required parameter that array_rand() takes.

$number_of_items: [Optional] This is the int value that shows how many random keys you want to get from the array. Its value is set to 1 by default.

Example:-

<?php
    $my_arr = ["Vijay", "Amit", "Dharmu", "Rahul", "Ravi"];

    $rand_index = array_rand($my_arr);

    echo $my_arr[$rand_index];
?>

Output:-

The output will be different each time you execute the above code. If you want to get more than 1 random key from the array you can use the below code example.

Example:

<?php
    $my_arr = ["Vijay", "Amit", "Dharmu", "Rahul", "Ravi"];

    $rand_index = array_rand($my_arr, 2);

    echo $my_arr[$rand_index[0]];
    echo $my_arr[$rand_index[1]];
?>

Output:-

shuffle() function

If you’re looking for a quick and easy way to get a random item from an array using PHP, the shuffle() function is the way to go. This function will randomly shuffle the items in an array, making it easy to get a random item.

Syntax:-

shuffle($arr)[0];

Example:-

<?php
    $my_arr = [
        "a" => 100,
        "b" => 200,
        "c" => 300,
        "4" => 400
    ];

    shuffle($my_arr);

    echo $my_arr[0];
?>

Output

How to emove duplicate values from PHP Array? explain with example

PHP array_unique

PHP array_unique() function to remove duplicate elements or values from an array. If the array contains the string keys, then this function will keep the first key encountered for every value, and ignore all the subsequent keys.

Example:-

<?php
   $array = array("a" => "One", "Tow", "One" => "Tow", "Three", "Four");
 
   // Deleting the duplicate items
   $result = array_unique($array);
   print_r($result);
?> 

Output:-

Removing duplicate values from an array in PHP

To remove duplicate values from an array in PHP, use the array_unique() function. If two or more array values are the same, the first appearance will be kept, and the other will be removed. The returned array will hold the first array item’s key type.

Syntax:-

array_unique(array, [sortingType])

Arguments

The array parameter is required, which specifies the array.

sortingType parameter is optional, and it specifies how to compare the array element. The following are some soringType flags.

  1. SORT_REGULAR – compare items usually (don’t change types)
  2. SORT_NUMERIC – compare items numerically
  3. SORT_STRING – compare items as strings
  4. SORT_LOCAL_STRING – compare items as strings based on the current locale.

Example:-

<?php

   $data = [20, 21, 21, 22, 21, 23, 22, 46, 47];

   print_r(array_unique($data));

?> 

Output:-

Associative Array in PHP array_unique() Function

Let’s pass the associative array to the array_unique function and see the output.

Example:-

<?php

    $data = ['a' => 'Vijay', 
        'b' => 'Amit',
        'd' => 'Vijay', 
        'f' => 'Amit', 
        'c' => 'Rahul', 
        'k' => 'Roshan', 
        'n' => 'Vijay'];
    $output = array_unique($data);
    print_r($output);

?> 

Output:-

Create a multidimensional array unique

You can create a multidimensional array unique for any single key index. 

Example:-

<?php

    function unique_multi_array($array, $key) { 
    $temp_array = array(); 
    $i = 0; 
    $key_array = array(); 
    
    foreach($array as $val) { 
        if (!in_array($val[$key], $key_array)) { 
            $key_array[$i] = $val[$key]; 
            $temp_array[$i] = $val; 
        } 
        $i++; 
    } 
    return $temp_array; 
  }
  
  $data = array( 
    0 => array("id"=>"1", "name"=>"Vijay",  "age"=>"26"), 
    1 => array("id"=>"2", "name"=>"Amit", "age"=>"25"), 
    2 => array("id"=>"1", "name"=>"Rahul",  "age"=>"26"), 
  ); 
  $output = unique_multi_array($data,'id');
  print_r($output);

?> 

Output:-

What is the difference between count or sizeof function in PHP? explain with example

According to PHP official documentation, there is no difference between count() or sizeof() function in PHP, which means both are the same, the sizeof() function is just the alias of count function i.e. the sizeof() uses the same as count function underneath. Both are used to count elements in an array.sizeof() function is an alias of count() function used in PHP. count() function is faster and butter than sizeof().

count() method: 

The count() method is used to calculate all the elements in the array or any other countable object. It can be used for both uni-dimensional as well as multi-dimensional arrays. 

count(array)

Example:-


<?php
        $parts = array(

                "Ram" => array(
                "SSD",
                "Processor"
            ),
                "Key" => array(
                "Monitor"  
            ),
                "Mouse" => array(
                "Cebal"
            )
        );
        
        print_r($parts);
        print("<br>");
        
        echo "Sub elements of an array: "
            . count($parts) . "<br>";
        echo "All elements of an array: "
            . count($parts, 1);
        
?>

Output:-

sizeof() method: 

The sizeof() method is used to calculate all the elements present in an array or any other countable object. It can be used for both uni-dimensional as well as multi-dimensional arrays. 

sizeof(arr, mode)

Example:-

<?php
    $parts = array(

        "Computer" => array(
        "SSD",
        "Processor"
    ),
        "Keyboard" => array(
        "Monitor"  
    ),
        "Mouse" => array(
        "CPU"
    )
);
    
    print_r($parts);
    print("<br>");
    
    echo "Sub elements of an array: "
        . sizeof($parts) . "<br>";
    echo "All elements of an array: "
        . sizeof($parts, 1);
 
?>

Output:-

Difference between sizeof() and count() methods:

  • The sizeof() method takes a longer execution time.
  • The sizeof() method is an alias of the count() method.
count() sizeof()
1. The count() returns the number of elements in the array.The sizeof() function is used to return the number of elements in an array.
2. Its syntax is -:
count(array, mode)
Its syntax is -:
sizeof(array, mode)
3. Its return value is of integer type.Its return value is of integer type.
4. The count() function may return 0 for a variable that is not set.This function is an alias of count() function.
5. It is supported in PHP version 4.0+It is supported in PHP version 4.0+

How to convert a JSON string to an array in PHP? explain with example

To convert the PHP array to JSON, use the json_encode() function. The json_encode() is a built-in PHP function that converts an array to json. The json_encode() function returns the string containing a JSON equivalent of the value passed to it, as demonstrated by the numerically indexed array. We can also convert any JSON received from a server into JavaScript objects.

Objects and arrays can be converted into JSON using the json_encode() method.

Example:-

<?php

    $netflix = ['Black Mirror', '13 Reasons Why', 'Bird Box', 'Dirt'];

    $netJSON = json_encode($netflix);

    echo $netJSON."\n";
    
?>

Output

A numerically indexed PHP array is translated to the array literal in a JSON string. JSON_FORCE_OBJECT option can be used if you want that array to be output as the object instead.

Convert Associative Array to JSON

Let’s take the example of converting a key-value pair array to json.

Example:-

<?php

    $data = ['name' => 'Vijay', 'blog' => 'AppDividend', 'education' => 'BE'];
    $jsonData = json_encode($data);
    echo $jsonData."\n";
    
?>

Output:-

List functions available to sort a php array? Explain with an Example.

PHP comes with a number of built-in functions designed specifically for sorting array elements in different ways like alphabetically or numerically in ascending or descending order. Here we’ll explore some of these functions most commonly used for sorting arrays.

Syntax:-

sort(array &$array, int $flags = SORT_REGULAR): bool

PHP array sort function examples

1) Using the PHP sort() function to sort an array of numbers

This example uses the PHP sort() function to sort an array of three numbers:

<?php

    $numbers = [2, 1, 3];
    sort($numbers);

    print_r ($numbers);
    
?>

Output:-

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

2) Using the PHP sort() function to sort an array of strings

This example uses the sort() function to sort an array of strings alphabetically:

<?php

    $names = ['Bob', 'John', 'Alice'];
    sort($names, SORT_STRING);

    print_r($names);
    
?>

Output:-

Array
(
    [0] => Alice
    [1] => Bob
    [2] => John
)

3) Using the PHP sort() function to sort an array of strings case-insensitively

<?php

    $fruits = ['apple', 'orange', 'banana', 'pink' ];
    sort($fruits);

    print_r($fruits);
    
?>

Output:-

4) Using the PHP sort() function to sort an array of strings using “natural ordering”

To sort an array of strings in the “natural ordering”, you combine the SORT_STRING  SORT_NATURAL flags.

Example:-

<?php

    $ranks = ['A-1', 'A-12', 'A-2',  'A-11'];
    sort($ranks, SORT_STRING | SORT_NATURAL);

    print_r($ranks);
    
?>

Output:-

How to Delete an element from an array? explain with example

One of the most common tasks in PHP is deleting an element from an array. We will introduce methods to delete an element from an array in PHP.

  • Using unset() function
  • Using array_splice() function
  • Using array_diff() function

Using the unset() Function

Use unset() Function to Delete an Element From an Array in PHP

The built-in function unset() is used to delete the value stored in a variable. It is only applicable to the local variables. It does not reflect its behavior on global variables. We can use this function to delete an element from an array.

unset($variableName);

It has a single mandatory parameter. The variable whose value we wish to delete is passed as a parameter to this function.

Example:-

<?php
   //Declare the array
   $nicname = array(
                "Vijay",
                "Amit",
                "Rahul",
                "Dharmendra",
                "Roshan");

   unset($nicname[2]);
   echo "The array is:\n";
   print_r($nicname);
?>

This function can delete one value at a time. The name of the array along with the element index ($nicname[2]) is passed as a parameter. This function does not change the index values. The index values remain the same as they were before.

Output:

As you could see, the index 1 is missing after we apply the unset function.

Use array_splice() Function to Delete an Element From an Array in PHP

The function array_splice() is used to add elements to an array or delete elements from an array.

array_splice($arrayName, $startingIndex, $numOfElements, $array2Name);

It has four parameters.

  1. $arrayName is a mandatory parameter. It is the array whose elements will be deleted.
  2. $startingIndex is the index of the element we wish to delete.
  3. $numOfElements is the number of elements we want to delete from the starting index.
  4. $array2Name is an array of elements we want to add.
<?php
//Declare the array
$nicname = array(
                "Vijay",
                "Amit",
                "Dharmu",
                "Roshan",
                "Dilip",
                "Rahul",
                "Dhyanchand",
                "Shohan");

array_splice($nicname, 4, 3);
echo "The array is:\n";
print_r($nicname);
?>

The array $nicname is passed as a parameter to this function along with the starting index 4 and the number of elements we want to delete-3. In this way, we can delete multiple elements from an array.

Output:-

Different from unsetarray_splice the function will automatically reindex the keys.

Daisy has the new index as 4 but not the original index – 7, after we delete three elements before it.

Use array_diff() Function to Delete an Element From an Array in PHP

The built-in function array_diff() finds the difference between two or more arrays. It can be used to delete multiple values from an array without affecting their indexes.

array_diff($array1, $array2, $array3, ... , $arrayN);

It takes N number of arrays as the parameters. It compares the first array with all other arrays and returns an array that contains all the elements of the first array that are not present in other arrays.

<?php
//Declare the array
$nicname = array(
                "Vijay",
                "Amit",
                "Dharmu",
                "Roshan",
                "Rahul",
                "Devanand",
                "Ramayan",
                "Dillyan");

$nicname = array_diff($nicname, array("Vijay","Amit"));
echo "The array is:\n";
print_r($nicname);
?>

Here, the first array that we have passed is $nicname and the second array contains the elements that we want to delete from $nicname. This function does not change the indexes of the elements of the array.

Output:-

How to create an array from a PHP string? explain with example

You can use the array() function with comma strings passed as an argument to it, to create an array of strings.

Syntax:-

$arr = array( 
string1, 
string2, 
string3 );

You can use create an empty array first using the array() function and then assign strings using offset. The syntax is

$arr = array();
$arr[0] = "string1";
$arr[1] = "string2";

we will create an empty array and then assign strings as elements to it using index/offset.

<?php
$arr = array();
$arr[0] = "bus";
$arr[1] = "car";
$arr[2] = "trains";
?>

Echo String Array

You can use the echo construct and implode() function to display all elements of the string array to a browser. In the following example, we will display all elements of a string array, separated by a single space.

<?php
   $arr = array(
          "bus",
          "car",
          "trains"
   );

   $arrString = implode(" ", $arr);

   echo $arrString;
?>

Output:-

Iterate over Strings of String Array

To iterate over individual strings of a string array, you can use foreach loop, for loop, while loop, etc. In the following example, we will use a PHP foreach loop to iterate over elements of a string array.

Example:-

<?php
    $arr = array(
       "Maruti",
       "Mahindra",
       "Honda"
    );
    foreach ($arr as $string) {
      echo " " , $string;
    }
?>

Output:-

What is the difference between array_merge and array_combine?

The array_merge() function is used to merge two or more arrays into a single array. This function is used to merge the elements or values of two or more arrays together into a single array. The merging occurs in such a manner that the values of one array are appended at the end of the previous array. The function takes the list of arrays separated by commas as a parameter that is needed to be merged and returns a new array with merged values of arrays passed in the parameter.

array_merge()

Syntax:

array array_merge( $array1, $array2)

 array1 is the first array with keys and array2 is the second array with the values.

<?php
  
    $array1 = array("subject1" => "Aajay","subject2" => "Vijay");
  
    $array2 = array("subject3" => "Sanjay","subject4" => "Jay");
  
    $final = array_merge($array1, $array2);

    print_r($final);
  
?>

Output:-

Array
(
    [subject1] => Ajay
    [subject2] => Vijay
    [subject3] => Sanajy
    [subject4] => Jay
)

array_combine()

The array_combine() function is used to combine two arrays and create a new array by using one array for keys and another array for values i.e. all elements of one array will be the keys of the new array and all elements of the second array will be the values of this new array.

Syntax:

array_combine(array1, array2)

Example: 

<?php
  
   // Define array1 with keys 
   $array1 = array("subject1" ,"subject2");
  
   // Define array2 with  values
   $array2 = array( "Vijay", "Ram");
  
   // Combine two arrays
   $final = array_combine($array1, $array2);
  
   // Display merged array
   print_r($final);
  
?>

Output:-

Array
(
    [subject1] => Vijay
    [subject2] => Ram
)

How to get number of elements in an Array? explain with example

PHP offers count() and sizeof() functions. The count() and sizeof() both functions are used to count all elements in an array and return 0 for a variable that has been initialized with an empty array. These are the built-in functions of PHP. We can use either count() or sizeof() function to count the total number of elements present in an array.

Syntax:

count(array)

Example:-

<?php
  $days = array("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat");
 

  echo 'Total number of elements in the $days array is - ' . count($days);
  echo "<br>";
  echo 'Total number of elements in the $days array is - ' . sizeof($days);
?>  

Output:-

Total number of elements in the $days array is - 7
Total number of elements in the $days array is - 7

How to create an empty array in PHP? explain with example

When an empty array and then start entering elements in it later. With the help of this, it can prevent different errors due to a faulty array. It helps to have the information of using bugged, rather than having the array. It saves time during debugging. Most of the time it may not have anything to add to the array at the point of creation.

Syntax to create an empty array:

$emptyArray = []; 
$emptyArray = array();
$emptyArray = (array) null;

While push an element to the array it can use $emptyArray[ ] = “first”. At this time, $emptyArray contains “first”, with this command and sending “first” to the array which is declared empty at starting.

In other words, the initialization of the new array is faster, use syntax var first = [ ] rather than using syntax var first = new Array(). The fact is being a constructor function the function Array() and the, [ ] is a part of the literal grammar of array. Both are complete and executed in completely different ways. Both are optimized and not bothered by the overhead of any of the calling functions.

Example:

<?php
  
    $emptyArray = (array) null;
  
    var_dump($emptyArray);
?>

Output:

array(0) {
}

PHP supports [ ] as an alternative, according to the respective compiler it was synonymous and most PHP developers use $array = [ ] because it makes it easier to go back and forth between JS and PHP.

<?php

    $firstempty = [];
    echo "Created First empty array <br>";


    $second = array( );
    echo "Created second empty array <br>";  


      
    
    $first = array( 1, 2);
          
    foreach( $first as $value ) {
      echo "Value is $value <br>";
     }
          

     $first[0] = "one";
     $first[1] = "two";
          
     foreach( $first as $value ) {
       echo "Value is $value <br>";
     }
?>

Output:

Created First empty array 
Created second empty array
Value is 1 
Value is 2 
Value is one 

How to Traverse an array in PHP and print?

The most common task with arrays is to do something with every element—for instance, sending mail to each element of an array of addresses, updating each file in an array of filenames, or adding up each element of an array of prices. There are several ways to traverse arrays in PHP, and the one you choose will depend on your data and the task you’re performing.

Example:-

<!DOCTYPE html>
<html>
	<body>
        <?php
            $array = array("Lux","Sampoo");

            foreach($array as $value) {
              print  " $value";
            }
        ?>
	</body>
</html>

Output:-

Lux Shampoo

Example:-

<!DOCTYPE html>
<html>
	<body>
        <?php
            $fnames = ["Amit", "Rahul", "Vijay", "Ravi", "Roshan"];

            $arrObject = new ArrayObject($fnames);
            $arrayIterator = $arrObject->getIterator();
                    
            while( $arrayIterator->valid() ){
                echo $arrayIterator->current() . "<br />";
                $arrayIterator->next();
            }
        ?>
	</body>
</html>

Output:-

What are the types of Array in PHP? Plz, provide an explanation with an example.

Types of PHP Arrays

There are 3 types of arrays in PHP.

  1. Indexed or Numeric Arrays
  2. Associative Arrays
  3. Multi-Dimensional Arrays

Indexed or Numeric Arrays

An index array is an array in which the values or items of the array are assigned by the index number. The name of the index array itself shows that the index number has importance in the index array. The index array has a different index number for each value. Index means 1, 2, 3, 4, 5 but index numbers in the index array start from 0. Index numbers are 0,1,2,3,4,etc.

$var = array("Value0", "Value1", "Value2");

Output

Associative Arrays

The associated array is a simple and very important array of PHP. This array is also used the most, it is also very easy to understand this array, as it contains keys and values. In simple language, the key acts as the name, and the value works as the information related to that name. For Mohan is a key and Mohan’s age or address, email, etc. are his values.

Example:-

Output

Multi-Dimensional Array

A multidimensional array is an array that uses more than one array, instead of storing a single element, it stores another array at each index.

Example:-

Output

What is Array in PHP? Write down the top 10 real use cases of Array in programming.

What is Array?

The array is a collection of items. The array is used for data types. The array is a special type of data structure that stores fixed-size data collection. We can store any amount of data in the array and use it easily. It also works like a database in which we can store the data. You can store it and use it. The array is a collection in which a lot of data can be stored. Array removes the complexity of the data. Many data problems can be removed by using PHP Array. The array() function is used to create an array. PHP array() function can contain (store, collect) many values.

Syntax of Array

array("value1", "value2 ", "value3");

In the above syntax, we have defined some values or items along with the array() function. PHP Array can also be defined as a database to store values. In the above syntax you can see value1, value2 and value3 in an array() function. These values(value1,value2,value3) can also be called item1,item2,item3 because array is a collection of similar items.

Examples of array

Example 1:-

<!DOCTYPE html>
<html>
  <body>
     <?php
       $fruits = array("Banana", "Mango ", "Orange");
       echo "I like " . $fruits[0] . ", " . $fruits[1] . " and " . $fruits[2] . ".";
?>
  </body>
</html>

Output

In the example above, we have created an array from a fruit variable. In Array, we have taken some items of fruits. The array contains index numbers. Index numbers start from 0 like – array(“Banana(0 index number )”, “Mango(1 index number ) “, “Orange(2 index number)”); Banana is stored at index number 0, Mango is stored at index number 1, and Orange is stored at index number 2.

Sometimes it goes out of our mind that array index numbers start from 0. If you think that array index numbers start with the number 1, then you are absolutely wrong. Keep in mind that Array index numbers start at 0. If an incorrect array index number is obtained, you will get an error or get another value. Array index numbers always start from 0.

We will also define the values one by one along with the index number of the array. This is another way to declare an array.

<?php 
   $x[0]=12;
   $x[1]=14;
   $x[2]=777;
   $x[3]=44;
?>
  <p>Sr No  
     <?php echo"$x[0]"; ?>
  </p>
  <p>Sr No 
     <?php echo "$x[1]"; ?>
  </p>
  <p>Sr No 
    <?php echo "$x[2]"; 
?>
  </p>
   Sr No <?php echo "$x[3]"; 
?>

Output:-

In the example above, we declared the array one after the other. $x is an array variable. In the first example, we used the variable once and we did not provide any type of index number, but in this example, we have defined different values with index numbers. So it is different from the first example.

Example 2:-

<?php 
   $odd_no= [1,3,5,7,9];
   $first_odd_number = $odd_no[0];
   $second_odd_number = $odd_no[1];
   $third_odd_number = $odd_no[2];
   $fourth_odd_number = $odd_no[3];

   echo "This is  first odd number = $first_odd_number";
   echo "<br>";
   echo "This is second odd number = $second_odd_number";
   echo "<br>";
   echo "This is  third odd number = $third_odd_number";
   echo "<br>";
   echo "This is fourth odd number = $fourth_odd_number";
?>

Output

This is first odd number = 1
This is second odd number = 3
This is third odd number = 5
This is fourth odd number = 7

Example 3:

<!DOCTYPE html>
<html>
	<body>
        <?php
            $age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
            echo "Peter is " . $age['Peter'] . " years old.";
        ?>
	</body>
</html>

Output

Peter is 35 years old.

Example 4:

<!DOCTYPE html>
<html>
	<body>
        <?php
            $cars=array("Volvo","BMW","Toyota");
            $arrlength=count($cars);

            for($x=0;$x<$arrlength;$x++)
            {
                echo $cars[$x];
                echo "<br>";
            }
        ?>
	</body>
</html>

Output

Volvo
BMW
Toyota

Example 5:

<!DOCTYPE html>
<html>
	<body>
    <?php
        $age=array("Ram"=>"35","Lakshman"=>"37","Bharat"=>"43");

            foreach($age as $x=>$x_value)
        {
            echo "Key=" . $x . ", Value=" . $x_value;
            echo "<br>";
        }
?>
	</body>
</html>

Output

Key=Ram, Value=35
Key=Lakshman, Value=37
Key=Bharat, Value=43

Example 5:-

<!DOCTYPE html>
<html>
	<body>
        <?php
            $color1 = "Red";
            $color2 = "Green";
            $color3 = "Blue";

            echo $color1;
            echo "<br>";

            echo $color2;
            echo "<br>";

            echo $color3;
        ?>
	</body>
</html>

Output

Red
Green
Blue

Example 6:-

<!DOCTYPE html>
<html>
	<body>
        <?php
            $foo = array(1, 2, 3);
            $bar = ["A", true, 123 => 5]; 
            echo $bar[0]; 
            echo $bar[1]; 
            echo $bar[123]; 
        ?>
	</body>
</html>

Output

A15

<!DOCTYPE html>
<html>
	<body>
        <?php
          $arrays = [[1, 2], [3, 4], [5, 6]];

          foreach ($arrays as list($a, $b)) {
             $c = $a + $b;
             echo($c . ', '); 
          }
        ?>
	</body>
</html>

Output

3, 7, 11,

Example 6:-

<!DOCTYPE html>
<html>
	<body>
        <?php
            $names[0] = "Rajesh";
            $names[1] = "Rakesh";
            $names[2] = "Abhishekh";
            echo $names[1] . " and " . $names[2] . " are ". $names[0] . "'s neighbors";
        ?>
	</body>
</html>

Output

Rakesh and Abhishekh are Rajesh’s neighbors

Example 7:-

<!DOCTYPE html>
<html>
	<body>
        <?php
                $animals = array("Line"=>"Sher", "Cow"=>"Gai", "Tiger"=>"Bhag");

                // loop through associative array and get key-value pairs
                
                foreach($animals as $name => $value) {
                
                    echo "Name=" . $name . ", Value=" . $value;
                
                    echo "</br>";
                
                }
        ?>
	</body>
</html>

Outputs

Name=Line, Value=Sher
Name=Cow, Value=Gai
Name=Tiger, Value=Bhag

Example 8:-

<!DOCTYPE html>
<html>
	<body>
        <?php
            for ($row = 0; $row < 3; $row++) {

                echo "<p>Row number $row</p>";
              
                echo "<ul>";
              
            }
        ?>
	</body>
</html>

Outputs

Example 9:-

<!DOCTYPE html>
<html>
	<body>
        <?php
            $arr_variable = array (1,2,3,4,5);
  
            foreach( $arr_variable as $arritem )
            {
                echo "The array item is: $arritem <br />";
            }
  
        ?>
	</body>
</html>

Outputs

The array item is: 1
The array item is: 2
The array item is: 3
The array item is: 4
The array item is: 5

Example 10:-

<!DOCTYPE html>
<html>
	<body>
        <?php
            $arr = array(
                "Apple",
                "Banana",
                "Cherry"
            );
            $arrString = implode(" ", $arr);
            echo $arrString;
        ?>
	</body>
</html>

Outputs

Apple Banana Cherry

We have created an array that takes odd numbers. As you know, odd numbers start with 1,3,5,7,9. An odd number means, which cannot be completely divided by 2. An odd number is divisible by the same odd number. That is, 7 is divided by 7 and 3 by 3, after that, we stored different array values ​​in different variables, and after that, we displayed array values ​​one after the other with the help of the echo() function.