0
0
PHPprogramming~5 mins

Array access and modification in PHP - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
How do you access the first element of an array in PHP?
Use the index 0 inside square brackets after the array variable. For example: $array[0] accesses the first element.
Click to reveal answer
beginner
How do you change the value of an element in a PHP array?
Assign a new value to the element using its index or key. For example: $array[2] = 'new value'; changes the third element.
Click to reveal answer
intermediate
What happens if you assign a value to an array index that does not exist yet?
PHP will add a new element at that index with the assigned value. This can create new elements dynamically.
Click to reveal answer
beginner
How do you add a new element to the end of an array without specifying an index?
Use empty square brackets to append: $array[] = 'new element'; adds the element at the end.
Click to reveal answer
beginner
How do you access an element in an associative array by key?
Use the key inside square brackets as a string. For example: $array['key'] accesses the element with that key.
Click to reveal answer
What does $array[1] return in PHP?
AThe first element of the array
BThe second element of the array
CThe last element of the array
DAn error
How do you add a new element to the end of an array without specifying the index?
ABoth A and C
B$array[] = 'value';
Carray_push($array, 'value');
D$array[0] = 'value';
What happens if you assign a value to $array[5] when the array has only 3 elements?
APHP adds a new element at index 5
BPHP throws an error
CPHP replaces the third element
DPHP ignores the assignment
How do you access the value associated with the key 'name' in an associative array?
A$array.name
B$array[name]
C$array->name
D$array['name']
Which of the following is the correct way to change the third element of an array to 10?
A$array(2) = 10;
B$array[3] = 10;
C$array[2] = 10;
D$array->2 = 10;
Explain how to access and modify elements in a PHP array.
Think about how you use square brackets with the array variable.
You got /3 concepts.
    Describe what happens when you assign a value to an array index that does not exist yet in PHP.
    PHP arrays are flexible and can grow as you assign new indexes.
    You got /3 concepts.