0
0
PHPprogramming~20 mins

Associative array creation in PHP - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Associative Array Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of associative array creation with mixed keys
What is the output of the following PHP code?
PHP
<?php
$arr = ["a" => 1, 2 => "b", "3" => "c", 4 => "d"];
print_r($arr);
?>
AArray ( [0] => a [1] => 1 [2] => b [3] => c [4] => d )
BArray ( [a] => 1 [2] => b [3] => c [4] => d [0] => 0 )
CArray ( [a] => 1 [2] => b [3] => c [4] => d )
DArray ( [a] => 1 [2] => b [3] => c )
Attempts:
2 left
💡 Hint
Remember that numeric string keys are converted to integers in PHP arrays.
Predict Output
intermediate
1:30remaining
Count items in associative array created with array()
How many items does the following associative array contain?
PHP
<?php
$assoc = array('x' => 10, 'y' => 20, 'z' => 30);
echo count($assoc);
?>
AError
B0
C1
D3
Attempts:
2 left
💡 Hint
Count returns the number of key-value pairs in an array.
🔧 Debug
advanced
2:00remaining
Identify the error in associative array creation
What error does the following PHP code produce?
PHP
<?php
$arr = ["key1" => 100, "key2" 200, "key3" => 300];
print_r($arr);
?>
AParse error: syntax error, unexpected '200' (missing =>)
BNotice: Undefined index 'key2'
CWarning: Array to string conversion
DNo error, outputs the array
Attempts:
2 left
💡 Hint
Check the syntax for key-value pairs in arrays.
🧠 Conceptual
advanced
1:30remaining
Associative array key type behavior
Which statement about PHP associative array keys is TRUE?
ANull keys are converted to string 'null'
BBoolean true is converted to integer 1 as a key
CArrays can be used as keys
DFloat keys are stored as floats
Attempts:
2 left
💡 Hint
Think about how PHP converts different types to keys internally.
🚀 Application
expert
2:30remaining
Create associative array from two lists
Given two arrays $keys = ['name', 'age', 'city'] and $values = ['Alice', 30, 'Paris'], which code correctly creates an associative array combining keys and values?
A$assoc = array_combine($keys, $values);
B$assoc = array_fill_keys($keys, $values);
C$assoc = array_map(fn($k, $v) => [$k => $v], $keys, $values);
D$assoc = array_merge($keys, $values);
Attempts:
2 left
💡 Hint
Look for a function that pairs keys and values into an associative array.