Skip to main content

Intro to PHP Homework

Welcome! These are some bonus puzzles to accompany the Intro to PHP class. Please take a look at the puzzles, and work on one that looks challenging but not completely overwhelming. You can always reference the slides if you get stuck. Commit to spend at least 20 minutes trying to figure out a problem before you look at the answers. It helps you learn!

Class 1

The Fortune Teller

Why pay a fortune teller when you can just program your fortune yourself?

  • Store the following into variables: number of children, partner's name, geographic location, job title.
  • Output your fortune to the screen like so: "You will be a X in Y and married to Z with N kids."
$numKids  = 5;
$partner  = 'David Beckham';
$geolocation = 'Costa Rica';
$jobTitle = 'web developer';

$future = "You will be a $jobTitle in $geolocation and married to $partner with $numKids kids.";
echo $future;

The Age Calculator

Forgot how old someone is? Calculate it!

  • Store the current year in a variable.
  • Store their birth year in a variable.
  • Calculate their 2 possible ages based on the stored values.
  • Output them to the screen like so: "They are either NN or NN", substituting the values.
$birthYear = 1984;
$currentYear  = 2016;
$age  = $currentYear - $birthYear;
echo "They are either $age or ".($age - 1);

The Temperature Converter

Let's make a program to convert celsius tempatures to fahrenheit and vice versa, so we can complain about the weather with our friends oversees.

Reminder: To convert celsius to fahrenheit, multiply by 9, then divide by 5, then add 32. To convert fahrenheit to celsius, deduct 32, then multiply by 5, then divide by 9.

  • Store a celsius temperature into a variable.
  • Convert it to fahrenheit and output "NN°C is NN°F".
  • Now store a fahrenheit temperature into a variable.
  • Convert it to celsius and output "NN°F is NN°C."
$inputCelsius  = 25;
$outputFahrenheit = ($inputCelsius * 9)/5 + 32;
echo "<p>$inputCelsius°C is $outputFahrenheit°F</p>";

$inputFahrenheit  = 73;
$outputCelsius = ($inputFahrenheit - 32)/9 * 5;
echo "<p>$inputFahrenheit°F is $outputCelsius°C.</p>";

Challenge Question: Using built-in functions

PHP has some built-in tools to handle common tasks. One is to rand, which will generate a random number for you. For example, rand(5, 15) will generate a random number between 5 and 15.

Using this tool, update your fahrenheit to celsius tempature conversion program to do the following:

  • Instead of inputing a value for the Fahrenheit tempature, use rand to generate a random tempature between 0 and 100
  • Have to program output: "It is NN°F today. That's NN°C."
$inputFahrenheit  = rand(0, 100);
$outputCelsius = ($inputFahrenheit - 32)/9 * 5;
echo "It is $inputFahrenheit°F today. That's $outputCelsius°C.";

Class 2

The Fortune Teller: With Functions!

Let's turn one of the Class 1 Exercises into a function.

  • Write a function named tellFortune that:
    • takes 4 arguments: number of children, partner's name, geographic location, job title.
    • outputs your fortune to the screen like so: "You will be a X in Y, and married to Z with N kids."
  • Call that function 3 times with 3 different values for the arguments.
function tellFortune($jobTitle, $geolocation, $partner, $numKids) {
  $future = "<p>You will be a $jobTitle in $geolocation and married to $partner with $numKids kids.</p>";
  echo $future;
}

tellFortune('bball player', 'Spain', 'Rhiana', 3);
tellFortune('stunt double', 'Japan', 'Ryan Gosling', 3000);
tellFortune('Elvis impersonator', 'Russia', 'The Oatmeal', 0);

What number is bigger?

Write a function that compares two numbers and returns the larger one. Be sure to try it out with some different numbers. Bonus: add error messages if the numbers are equal or cannot be compared.

Don't forget to test it!

function greaterNum($num1, $num2) {
  if ($num1 === $num2) {
    echo 'Those numbers are equal';
    return $num1;
  } else if ($num1 > $num2) {
    return $num1;
  } else if ($num2 > $num1) {
    return $num2;
  } else {
    echo 'Those are simply incomparable!';
    return undefined;
  }
}

echo greaterNum(3, 3);
echo greaterNum(7, -2);
echo greaterNum(5, 9);
echo greaterNum(5, 'dog');

Pluralize

Write a function pluralize that takes in two arguments, a number and a word, and returns the plural. For example:

pluralize(5, 'cat'): '5 cats'
pluralize(7, 'turtle'): '7 turtles'

Bonus: Make it handle a few collective nouns like "sheep" and "geese".

function pluralize($number, $noun) {
  if ($number != 1 && $noun != 'sheep' && $noun != 'geese') {
    return "$number ${noun}s";
  } else {
    return "$number $noun";
  }
}
echo 'I have ' . pluralize(0, 'cat');
echo 'I have ' . pluralize(1, 'cat');
echo 'I have ' . pluralize(2, 'cat');
echo 'I have ' . pluralize(3, 'geese');

The Calculator

  • Write a function called squareNumber that will take one argument (a number), square that number, and return the result. It should also echo a string like "The result of squaring the number 3 is 9."
  • Write a function called halfNumber that will take one argument (a number), divide it by 2, and return the result. It should also log a string like "Half of 5 is 2.5.".
  • Write a function called percentOf that will take two numbers, figure out what percent the first number represents of the second number, and return the result. It should also log a string like "2 is 50% of 4."
  • Write a function called areaOfCircle that will take one argument (the radius), calculate the area based on that, and return the result. It should also log a string like "The area for a circle with radius 2 is 12.566370614359172." (Hint: To include the value of pi in your function, use M_PI)
    • Bonus: Round the result so there are only two digits after the decimal.
  • Write a function that will take one argument (a number) and perform the following operations, using the functions you wrote earlier:
    1. Take half of the number and store the result.
    2. Square the result of #1 and store that result.
    3. Calculate the area of a circle with the result of #2 as the radius.
    4. Calculate what percentage that area is of the squared result (#3).
function squareNumber($num) {
  $squaredNumber = $num * $num;
  echo "The result of squaring the number $num is $squaredNumber";
  return $squaredNumber;
}

squareNumber(3);

function halfOf($num) {
  $half = $num / 2;
  echo "Half of $num is $half";
  return $half;
}

halfOf(5);

function percentOf($num1, $num2) {
  $percent = ($num1/$num2) * 100;
  echo "$num1 is ${percent}% of $num2";
  return $percent;
}

percentOf(5, 10);

function areaOfCircle($radius) {
  $area = M_PI * squareNumber($radius);
  echo "The area of circle with $radius radius is $area";
  return $area;
}

areaOfCircle(2);

function doCrazyStuff($num) {
  $half    = halfOf($num);
  $squared = squareNumber($half);
  $area    = areaOfCircle($squared);
  $result  = percentOf($squared, $area);
}

doCrazyStuff(5);

Challenge Question: String Manipulation

If you feel comfortable with the other exercises, it's time to expand your knowledge! These puzzles involve manipulating strings; to try them out, you'll need to use some of the built-in PHP string functions

These questions are not as straightforward as the others. They challenge you to really think like a programmer. Really try to solve them before you peek at the answer.

MixUp

Create a function called mixUp. It should take in two strings, and return the concatenation of the two strings (separated by a space) slicing out and swapping the first 2 characters of each. You can assume that the strings are at least 2 characters long. For example:

mixUp('mix', 'pod'): 'pox mid'
mixUp('dog', 'dinner'): 'dig donner'
//This function uses the substr() function. It extracts a part of a string and returns a new string
function mixUp($string1, $string2) {
  //new first word
  $newFirst =  substr($string2, 0, 2) . substr($string1, 2);

  //new second word
  $newSecond=  substr($string1, 0, 2) . substr($string2, 2);

  return "$newFirst $newSecond";
}
echo mixUp('mix', 'pod');
echo mixUp('dog', 'dinner');

FixStart

Create a function called fixStart. It should take a single argument, a string, and return a version where all occurrences of its first character have been replaced with '*', except for the first character itself. You can assume that the string is at least one character long. For example:

fixStart('babble'): 'ba**le'
fixStart('turtle'): 'tur*le'
function fixStart($inputString) {
  //Get the first character
  $firstChar = substr($inputString, 0, 1);

  //Seperate out the rest of the word
  $restOfWord = substr($inputString, 1);

  //Replace the first letter with a *
  $restOfWord = str_replace ($firstChar, '*' , $restOfWord);

  //Put the word back together and return it
  return "${firstChar}${restOfWord}";
}
echo fixStart('babble');
echo fixStart('turtle');
echo fixStart('kitten');

Class 3

Coming Soon

Even/Odd Counter

Write a for loop that will iterate from 0 to 20. For each iteration, it will check if the current number is even or odd, and report that to the screen (e.g. "2 is even")

for ($i = 0; $i <= 20; $i++) {
  if ($i % 2 === 0) {
    echo "$i is even<br />";
  } else {
    echo "$i is odd<br />";
  }
}

Top Choice

Create an array to hold your top choices (colors, presidents, whatever). For each choice, echo to the screen a string like: "My #1 choice is blue."

Bonus: Change it to "My 1st choice, "My 2nd choice", "My 3rd choice", picking the right suffix for the number based on what it is. The function substr might be helpful here.

//Simple code
$choices = array('red', 'orange', 'pink', 'yellow');
foreach ($choices as  $key => $value)  {
  echo "My #" . ($key + 1) . " choice is $value<br />";
}

//Bonus solution

//This is a giant array, to test for tons of cases.
$choices = ['Tiger' , 'Puss' , 'Smokey' , 'Misty' , 'Tigger' , 'Kitty' , 'Oscar' , 'Missy' , 'Max' , 'Ginger' , 'Molly' , 'Charlie' , 'Poppy' , 'Smudge' , 'Millie' , 'Daisy' , 'Jasper' , 'Felix' , 'Sooty' , 'Alfie' , 'Minou' , 'Grisou' , 'Ti-Mine' , 'Félix' , 'Caramel' , 'Mimi' , 'Pacha' , 'Charlotte' , 'Minette' , 'Chanel'];

foreach ($choices as  $key => $value)  {
  $choiceNum = $key + 1;

  /*Let's figure out the right suffix! Rules:
  Use st for numbers ending in 1 (1st, 21st, 31st) EXCEPT 11 (11th)
  Use nd for numbers ending in 2 (2nd, 22nd, 32nd) EXCEPT 12 (12th)
  Use rd for numbers ending in 3 (3rd, 23rd, 33rd) EXCEPT 13 (13th)
  Use th for all other numbers*/

  //th is the defaut choice, so we will use it as the initial value
  $choiceNumSuffix = 'th';
  //Then change it for our special classes
  if ($choiceNum <= 10 || $choiceNum >= 14){
    $lastDigit = substr($choiceNum, -1);
    if ($lastDigit == 1) {
      $choiceNumSuffix = 'st';
    } else if ($lastDigit == 2) {
      $choiceNumSuffix = 'nd';
    } else if ($lastDigit == 3) {
      $choiceNumSuffix = 'rd';
    }
  }

  echo "My $choiceNum$choiceNumSuffix choice is $value<br />";
}

The Reading List

Keep track of which books you read and which books you want to read!

  • Create an object class called book, with properties for the title (a string), author (a string), and alreadyRead (a boolean indicating if you read it yet).
  • Add a constructor for this object.
  • Create at least two instances of the book object.
  • Create a method that describes the book. Use an if/else statement to change the output depending on whether you read it yet or not. If you read it, echo a string like 'You already read "The Hobbit" by J.R.R. Tolkien', and if not, echo a string like 'You still need to read "The Lord of the Rings" by J.R.R. Tolkien.'
  • Now
class book {
  public $title;
  public $author;
  public $alreadyRead;

  public function __construct($title, $author, $alreadyRead) {
    $this->title = $title;
    $this->author = $author;
    $this->alreadyRead = $alreadyRead;
  }

  public function describeBook() {
    if ($this->alreadyRead){
      return "You already read \"$this->title\" by $this->author";
    } else{
      return "You still need to read \"$this->title\" by $this->author";
    }
  }
}

$firstBook = new book("Colson Whitehead", "The Underground Railroad" , true);
$secondBook = new book("Nicola Yoon", "The Sun Is Also a Star" , false);

echo $firstBook->describeBook();
echo $secondBook->describeBook();

Class 4

Coming soon!