PHP find output programs (Arrays) | set 3

Find the output of PHP programs | Arrays | Set 3: Enhance the knowledge of PHP Arrays concepts by solving and finding the output of some PHP programs.
Submitted by Nidhi, on January 22, 2021

Question 1:

<?php
    $TwoDArr = array(
        array(
            "Rahul" => "101",
            "Rohit" => "102",
            "Virat" => "103"
        ) ,
        array(
            10,
            20,
            30
        ) ,
        array(
            "ABC",
            "PQR",
            "XYZ"
        )
    );
    
    echo $TwoDArr[0]['Rahul'] . ' ' . $TwoDArr[0]['Rohit'] . ' ' . $TwoDArr[0]['Virat'];
    
    echo '<br>';
?>

Output:

101 102 103

Explanation:

The above program will print the values of the inner associative array. the associative array is located on index 0. Then $TwoDArr[0]['Rahul'] will access value "101".

Question 2:

<?php
    $Arr = array(
        8,
        5,
        2,
        4,
        9
    );
    
    $Arr . sort();
    
    foreach ($Arr as $Val)
    {
        echo $Val . ' ';
    }
?>

Output:

8 5 2 4 9

Explanation:

The above program will not print sorted array, because we did not use sort() function in the correct the way. The correct way to use the sort() function is given below,

sort($Arr);

Question 3:

<?php
    $Arr = array(
        8,
        5,
        2,
        4,
        9
    );
    
    rsort($Arr);
    
    foreach ($Arr as $Val)
    {
        echo $Val . ' ';
    }
?>

Output:

9 8 5 4 2

Explanation:

The above program will print a sorted array in descending order. Because rsort() function is used to sort index based array in descending order. Then we accessed each element using the foreach loop and print them on the webpage.

Question 4:

<?php
    $Arr = array(
        8,
        5,
        2,
        4,
        9
    );
    ksort($Arr);
    
    foreach ($Arr as $Val)
    {
        echo $Val . ' ';
    }
?>

Output:

8 5 2 4 9

Explanation:

In the above program, we used ksort() function, which is used to sort an associative array in ascending order. But we used ksort() function with indexed array then it will not array then print array as it is.

Question 5:

<?php
    $Arr = array(
        3 => "XYZ",
        5 => "PQR",
        1 => "ABC"
    );
    
    krsort($Arr);
    
    foreach ($Arr as $Val)
    {
        echo $Val . ' ';
    }
?>

Output:

PQR XYZ ABC

Explanation:

The above program will print "PQR XYZ ABC" on the webpage. The krsort() function is used to sort the associative array in descending array based on keys.

Here, we declared an associative array $Arr, then we sort() array using krsort() function in descending order based on keys.





Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.