Bird
0
0

You have an associative array of products with prices:

hard📝 Application Q8 of 15
PHP - Arrays
You have an associative array of products with prices:
$products = ['apple' => 3, 'banana' => 1, 'pear' => 2];
How do you sort this array by price descending while keeping product names as keys?
Asort($products)
Barsort($products)
Cksort($products)
Drsort($products)
Step-by-Step Solution
Solution:
  1. Step 1: Identify sorting by values descending with keys preserved

    arsort() sorts values descending and keeps keys intact.
  2. Step 2: Confirm other options

    sort() and rsort() reset keys; ksort() sorts keys, not values.
  3. Final Answer:

    arsort($products) -> Option B
  4. Quick Check:

    arsort() = values descending, keys preserved [OK]
Quick Trick: Use arsort() to sort values descending and keep keys [OK]
Common Mistakes:
  • Using sort() or rsort() which reset keys
  • Using ksort() which sorts keys
  • Expecting keys to change order

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PHP Quizzes