User Tools

Site Tools


php_variables

PHP Variables

  • The second Roger/Charles class, on Oct. 14, 2022.

Variables

What's a variable and what can you do with it?

First, we already saw we can store something from readLine() in a variable:

<?php

	$n = readLine("What is your name? ");
	$f = readLine("What is your favourite fruit? ");

	echo "Hello, Mr. ";
	echo $n . "!\n";
	echo "Do you want to eat " . $f . "?\n";

?>

Operations

We can add variables together.

<?php

	$a = readLine("a = ");
	$b = readLine("b = ");

	echo $a . " + " . $b . " = " . $a+$b . "\n";

?>

Testing variables with IF

We can also determine what to do based on what's in a variable.

<?php

	$name = readLine("What is your name? ");
	$fruit = readLine("What is your favourite fruit? ");

	if ($fruit == "poo") {
		echo "Ewwwwww!\n";
		echo $name . " is bad!\n";
	} else if ($fruit == "banana") {
		echo "{$name} is good.\n";
		echo "I also like {$fruit}. Yum!\n";
	} else {
		echo "Hello, {$name}.\n";
	}

?>

Integers

We can also store numbers and do operations on those numbers.

<?php

	$a = 5172;
	$b = 171;

	echo $a * $b;

	echo "\n";
?>
php_variables.txt · Last modified: 2024/10/06 05:16 by appledog

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki