0
0
PHPprogramming~10 mins

Array access and modification in PHP - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to access the first element of the array.

PHP
<?php
$fruits = ['apple', 'banana', 'cherry'];
echo $fruits[[1]];
?>
Drag options to blanks, or click blank then click option'
A3
B1
C2
D0
Attempts:
3 left
💡 Hint
Common Mistakes
Using 1 as the first index instead of 0.
Using an index outside the array range.
2fill in blank
medium

Complete the code to change the second element of the array to 'orange'.

PHP
<?php
$colors = ['red', 'green', 'blue'];
$colors[[1]] = 'orange';
print_r($colors);
?>
Drag options to blanks, or click blank then click option'
A1
B0
C2
D3
Attempts:
3 left
💡 Hint
Common Mistakes
Changing the wrong index.
Using an index that does not exist.
3fill in blank
hard

Fix the error in the code to correctly add a new element 'pear' to the array.

PHP
<?php
$fruits = ['apple', 'banana'];
$fruits[1] = 'pear';
print_r($fruits);
?>
Drag options to blanks, or click blank then click option'
A[2]
B[3]
C[]
D(2)
Attempts:
3 left
💡 Hint
Common Mistakes
Using parentheses instead of square brackets.
Using an index that skips positions.
4fill in blank
hard

Fill both blanks to create an associative array with keys as names and values as ages.

PHP
<?php
$ages = [[1] => 25, [2] => 30];
print_r($ages);
?>
Drag options to blanks, or click blank then click option'
A'Alice'
B'Bob'
C'Charlie'
D'David'
Attempts:
3 left
💡 Hint
Common Mistakes
Using numbers as keys without quotes.
Forgetting quotes around string keys.
5fill in blank
hard

Fill all three blanks to create an array of squares for numbers greater than 3.

PHP
<?php
$numbers = [1, 2, 3, 4, 5];
$squares = [[1] => [2] for [3] in $numbers if [3] > 3];
print_r($squares);
?>
Drag options to blanks, or click blank then click option'
A$num
B$num * $num
C$number
D$number * $number
Attempts:
3 left
💡 Hint
Common Mistakes
Using different variable names inconsistently.
Not squaring the number correctly.