Code Challenge 2
Posted on 25. Feb, 2010 by admin in Basics
Up for another code challenge? Since the first code challenge we have covered string functions and conditions. Let’s see how much you know. Again, no cheating!
Questions
Q: Write a line of code combining two string variables, $var and $var2, into $var3.
Show Answer ▼
Q: What is an escape character?
Show Answer ▼
Special syntax that allows us to use some characters that don’t work regularly.
Q: List the 6 most important escape characters we discussed.
Show Answer ▼
- Newline – \n
- Tab – \t
- Single Quote – \’
- Double Quote – \”
- Dollar Sign – \$
- Backslash – \\
Q: Write a line of code that prints the length of this string literal, “How many cookies can I eat?”
Show Answer ▼
echo strlen("How many cookies can I eat?");
Q: What does an else statement do?”
Show Answer ▼
Runs if none of the if or elseif statements are true.
Q: What are 3 differences between if and switch statements?”
Show Answer ▼
- Switch does not use brackets for each test
- If statements don’t use break;
- If statements use else and switch uses default
Programming Projects
Project One: Write a program that reverses a string if it is more than 10 characters long.
Show Answer ▼
<?php
//Test String
$string = "this is a test string";
//If Statement
if(strlen($string) >10) {
$string = strrev($string);
}
//Print it
echo $string;
?>
Project Two: Write a program that checks if a string is a palindrome.
Show Answer ▼
<?php
//Start string
$string = "Able was I ere I saw Elba";
//Start string reversed
$string2 = strrev($string);
//Lowercase just to make sure
$string = strtolower($string);
$string2 = strtolower($string2);
//Remove spaces
$string = str_replace(" ", "", $string);
$string2 = str_replace(" ", "", $string2);
//If Statement
if($string == $string2) {
echo "It is a palindrome!";
}
else {
echo "It is not a palindrome!";
}
?>