1, "Green" => 2, "Blue" => 3);
asort($colors);
foreach ($colors as $color => $value) {
echo "$color: $value ";
}
? | PHP | MYTAT"> 1, "Green" => 2, "Blue" => 3);
asort($colors);
foreach ($colors as $color => $value) {
echo "$color: $value ";
}
? | PHP | MYTAT">
Q
What will be the output of the following PHP code?
<?php
$colors = array('Red' => 1, 'Green' => 2, 'Blue' => 3);
asort($colors);
foreach ($colors as $color => $value) {
echo '$color: $value ';
}
?

Answer & Solution

Answer: Option Blue: 3 Green: 2 Red: 1
Solution:
The output of the code will be Blue: 3 Green: 2 Red: 1 because the asort() function in PHP sorts an associative array in ascending order based on the values while maintaining the key-value pairs intact. The foreach loop then iterates over the sorted array, printing each color-value pair in the sorted order.
Related Questions on Average

Which PHP function is used to determine the number of elements in an array?

A). size()

B). count()

C). length()

D). elements()

What will be the output of the following PHP code?
<?php
$numbers = array(10, 20, 30, 40, 50);
echo count($numbers);
?

A). 10

B). 20

C). 5

D). 50

What will be the output of the following PHP code?
<?php
$numbers = array(10, 20, 30, 40, 50);
array_pop($numbers);
foreach ($numbers as $number) {
echo $number . ' ';
}
?

A). 20 30 40 50

B). 10 20 30 40

C). 10 20 30 40

D). 10 20 30 40 50

Which PHP function is used to merge two or more arrays into a single array?

A). merge()

B). combine()

C). concat()

D). array_merge()

What will be the output of the following PHP code?
<?php
$person = array('name' => 'John', 'age' => 30, 'city' => 'New York');
echo $person['age'];
?

A). name: John

B). age: 30

C). city: New York

D). John

What will be the output of the following PHP code?
<?php
$info = array('name' => 'John', 'age' => 30, 'city' => 'New York');
echo array_key_exists('age', $info) ? 'Yes' : 'No';
?

A). Yes

B). No

C). John

D). 30

Which PHP function is used to extract a slice of an array?

A). splice()

B). slice()

C). extract()

D). split()

What is the purpose of the array_push() function in PHP?

A). To remove elements from an array

B). To add elements to the beginning of an array

C). To add elements to the end of an array

D). To reverse the order of elements in an array

Which PHP function is used to sort an array in ascending order, maintaining the key-value pairs?

A). sort()

B). ksort()

C). asort()

D). rsort()

What type of index do indexed arrays in PHP use?

A). String

B). Integer

C). Key-value pairs

D). Floating-point number