0
0
PHPprogramming~10 mins

String comparison functions 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 compare two strings for equality.

PHP
<?php
$string1 = "apple";
$string2 = "apple";
if ($string1 [1] $string2) {
    echo "Strings are equal.";
} else {
    echo "Strings are not equal.";
}
?>
Drag options to blanks, or click blank then click option'
A==
B===
C!=
D<>
Attempts:
3 left
💡 Hint
Common Mistakes
Using != which checks for inequality.
Using === which also checks type, not just value.
2fill in blank
medium

Complete the code to compare two strings ignoring case.

PHP
<?php
$string1 = "Hello";
$string2 = "hello";
if ([1]($string1, $string2) === 0) {
    echo "Strings are equal ignoring case.";
} else {
    echo "Strings are different.";
}
?>
Drag options to blanks, or click blank then click option'
Astrcmp
Bstrcasecmp
Cstrnatcmp
Dstrncmp
Attempts:
3 left
💡 Hint
Common Mistakes
Using strcmp which is case-sensitive.
Using strncmp which compares only part of the strings.
3fill in blank
hard

Fix the error in the code to correctly compare the first 3 characters of two strings.

PHP
<?php
$string1 = "abcdef";
$string2 = "abcxyz";
if (strncmp($string1, $string2, [1]) === 0) {
    echo "First 3 characters are equal.";
} else {
    echo "First 3 characters are different.";
}
?>
Drag options to blanks, or click blank then click option'
A2
B4
C3
D5
Attempts:
3 left
💡 Hint
Common Mistakes
Using 2 or 4 which compares wrong number of characters.
Confusing the argument with string length.
4fill in blank
hard

Fill both blanks to create an associative array with words as keys and their lengths as values, only for words longer than 4 characters.

PHP
<?php
$words = ["apple", "cat", "banana", "dog"];
$lengths = [
    [1] => strlen([2]) 
    for [1] in $words 
    if strlen([1]) > 4
];
?>
Drag options to blanks, or click blank then click option'
A$word
B$words
Cword
Dstrlen
Attempts:
3 left
💡 Hint
Common Mistakes
Using $words which is the whole array, not a single word.
Using word without $ which is invalid in PHP.
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 = ["pear", "fig", "grape", "kiwi"];
$result = [
    [1] => [2] 
    for [3] in $words 
    if strlen([3]) > 3
];
?>
Drag options to blanks, or click blank then click option'
Astrtoupper($word)
Bstrlen($word)
C$word
D$fruit
Attempts:
3 left
💡 Hint
Common Mistakes
Using different variable names inconsistently.
Not using strtoupper for the key.