0
0
PHPprogramming~20 mins

Array access and modification in PHP - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Array Access Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
What is the output of this PHP code?

Consider the following PHP code snippet:

$arr = [1, 2, 3, 4];
$arr[2] = $arr[0] + $arr[1];
echo $arr[2];

What will be printed?

PHP
$arr = [1, 2, 3, 4];
$arr[2] = $arr[0] + $arr[1];
echo $arr[2];
A5
B3
C6
DUndefined offset error
Attempts:
2 left
💡 Hint

Remember that array indices start at 0 and you can assign new values to existing keys.

Predict Output
intermediate
2:00remaining
What is the output after modifying a nested array?

Look at this PHP code:

$arr = ["a" => [1, 2], "b" => [3, 4]];
$arr["a"][1] = 5;
echo $arr["a"][1];

What will it print?

PHP
$arr = ["a" => [1, 2], "b" => [3, 4]];
$arr["a"][1] = 5;
echo $arr["a"][1];
A5
B2
C1
DUndefined index error
Attempts:
2 left
💡 Hint

Think about how to access and change values inside nested arrays.

🔧 Debug
advanced
2:00remaining
Identify the error in this array modification code

What error does this PHP code produce?

$arr = [10, 20, 30];
$arr[3] += 5;
echo $arr[3];
PHP
$arr = [10, 20, 30];
$arr[3] += 5;
echo $arr[3];
AOutputs 5
BNotice: Undefined offset: 3
CFatal error: Cannot use undefined offset
DOutputs 0
Attempts:
2 left
💡 Hint

Think about what happens when you try to add to an array element that does not exist yet.

📝 Syntax
advanced
2:00remaining
Which option causes a syntax error in array modification?

Which of the following PHP code snippets will cause a syntax error?

A
$arr = [1, 2, 3];
$arr[0] = $arr[0] + 1;
B
$arr = [1, 2, 3];
$arr[] = 4;
C
$arr = [1, 2, 3];
$arr[2] +=;
D
$arr = [1, 2, 3];
$arr[1] = 5;
Attempts:
2 left
💡 Hint

Look carefully at the assignment operators and their usage.

🚀 Application
expert
3:00remaining
How many elements are in the array after these modifications?

Given this PHP code:

$arr = [];
$arr[2] = 'a';
$arr[] = 'b';
$arr[5] = 'c';
$arr[] = 'd';

How many elements does $arr have after these lines run?

PHP
$arr = [];
$arr[2] = 'a';
$arr[] = 'b';
$arr[5] = 'c';
$arr[] = 'd';
A6
B3
C5
D4
Attempts:
2 left
💡 Hint

Remember how PHP assigns keys when using empty brackets and how explicit keys affect the array.