0
0
PHPprogramming~10 mins

Common validation patterns 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 a variable is set.

PHP
<?php
if ([1](
  $name
)) {
  echo "Name is set.";
} else {
  echo "Name is not set.";
}
?>
Drag options to blanks, or click blank then click option'
Aisset
Bempty
Cis_null
Dis_string
Attempts:
3 left
💡 Hint
Common Mistakes
Using empty() which returns true if the variable is empty, not just set.
Using is_null() which checks if variable is null but does not check if it is set.
2fill in blank
medium

Complete the code to validate if a string contains only digits.

PHP
<?php
if ([1]($input)) {
  echo "Input is numeric.";
} else {
  echo "Input is not numeric.";
}
?>
Drag options to blanks, or click blank then click option'
Ais_numeric
Bis_string
Cctype_digit
Dpreg_match
Attempts:
3 left
💡 Hint
Common Mistakes
Using is_numeric() which allows decimal points and signs.
Using preg_match without a proper pattern.
3fill in blank
hard

Fix the error in the code to validate an email address.

PHP
<?php
$email = "user@example.com";
if (filter_var($email, [1])) {
  echo "Valid email.";
} else {
  echo "Invalid email.";
}
?>
Drag options to blanks, or click blank then click option'
AFILTER_VALIDATE_INT
BFILTER_DEFAULT
CFILTER_SANITIZE_EMAIL
DFILTER_VALIDATE_EMAIL
Attempts:
3 left
💡 Hint
Common Mistakes
Using FILTER_SANITIZE_EMAIL which only cleans the email but does not validate.
Using FILTER_VALIDATE_INT which is for integers.
4fill in blank
hard

Fill both blanks to create an array of words longer than 3 characters.

PHP
<?php
$words = ['cat', 'house', 'dog', 'elephant'];
$longWords = array_filter($words, function($word) {
  return strlen($word) [1] [2];
});
print_r($longWords);
?>
Drag options to blanks, or click blank then click option'
A>
B<
C3
D5
Attempts:
3 left
💡 Hint
Common Mistakes
Using '<' instead of '>' causing wrong filtering.
Using 5 instead of 3 changing the condition.
5fill in blank
hard

Fill all three blanks to create an associative array of words and their lengths for words longer than 4.

PHP
<?php
$words = ['apple', 'bat', 'carrot', 'dog'];
$lengths = array_filter(array_combine(
  array_map(function($word) { return [1]; }, $words),
  array_map(function($word) { return [2]; }, $words)
), function($len) { return $len [3] 4; });
print_r($lengths);
?>
Drag options to blanks, or click blank then click option'
A$word
Bstrlen($word)
C>
D<
Attempts:
3 left
💡 Hint
Common Mistakes
Using '<' instead of '>' in the filter condition.
Using wrong variable names in map functions.