0
0
PHPprogramming~10 mins

Instanceof operator 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 check if $obj is an instance of the class MyClass.

PHP
<?php
class MyClass {}
$obj = new MyClass();
if ($obj [1] MyClass) {
    echo "Yes";
} else {
    echo "No";
}
?>
Drag options to blanks, or click blank then click option'
A===
B==
Cinstanceof
Dis_a
Attempts:
3 left
💡 Hint
Common Mistakes
Using == or === instead of instanceof.
Using is_a as if it were an operator.
2fill in blank
medium

Complete the code to check if $animal is an instance of the class Dog.

PHP
<?php
class Dog {}
class Cat {}
$animal = new Dog();
if ($animal [1] Dog) {
    echo "It's a dog.";
} else {
    echo "It's not a dog.";
}
?>
Drag options to blanks, or click blank then click option'
A==
Binstanceof
Cis_a
D===
Attempts:
3 left
💡 Hint
Common Mistakes
Using == or === which compare values, not types.
Trying to use is_a as an operator.
3fill in blank
hard

Fix the error in the code to correctly check if $obj is an instance of MyInterface.

PHP
<?php
interface MyInterface {}
class MyClass implements MyInterface {}
$obj = new MyClass();
if ($obj [1] MyInterface) {
    echo "Implements interface.";
} else {
    echo "Does not implement interface.";
}
?>
Drag options to blanks, or click blank then click option'
A===
B==
Cis_a
Dinstanceof
Attempts:
3 left
💡 Hint
Common Mistakes
Using == or === which do not check interface implementation.
Trying to use is_a as an operator.
4fill in blank
hard

Fill in the blank to create a dictionary with words as keys and their lengths as values, but only for words longer than 3 characters.

PHP
<?php
$words = ['apple', 'cat', 'banana', 'dog'];
$lengths = array_filter(array_combine($words, array_map(function($word) {
    return strlen($word);
}, $words)), function($length) {
    return $length [1] 3;
});
print_r($lengths);
?>
Drag options to blanks, or click blank then click option'
A>
B<
C==
D!=
Attempts:
3 left
💡 Hint
Common Mistakes
Using < or == which filter wrong lengths.
Using != which includes unwanted lengths.
5fill in blank
hard

Fill all three blanks to create an associative array with uppercase words as keys and their lengths as values, only for words longer than 3 characters.

PHP
<?php
$words = ['apple', 'cat', 'banana', 'dog'];
$lengths = array_filter(array_combine(array_map(function($word) {
    return [1];
}, $words), array_map(function($word) {
    return [2];
}, $words)), function($length) {
    return $length [3] 3;
});
print_r($lengths);
?>
Drag options to blanks, or click blank then click option'
A$word strtoupper($word)
Bstrlen($word)
C>
Dstrtoupper($word)
Attempts:
3 left
💡 Hint
Common Mistakes
Using $word instead of strtoupper($word) for keys.
Using wrong comparison operator in filter.
Mixing keys and values in array_combine.