80 likes | 197 Views
Intro to PHP. Coming from Java or C. How to Write PHP. Get a PHP file ( myfile.php ) Add a PHP tag <? php echo “Hello World”; ?> Run with a PHP interpreter (XAMPP is good for Windows). Variables. Declaration not necessary Variables have no type
E N D
Intro to PHP Coming from Java or C
How to Write PHP • Get a PHP file (myfile.php) • Add a PHP tag <?php echo “Hello World”; ?> • Run with a PHP interpreter (XAMPP is good for Windows)
Variables • Declaration not necessary • Variables have no type • All variables are preceded by a dollar sign $myVariable = 1;$myVariable = “Hello”; for($i = 0; $i < 22; $i++) { echo $i;}
String Concatenation • PHP likes to be unique • It likes to use periods instead of pluses$hello = “Hello ”; $world = “World”; echo $hello . $world; echo “Hello ” . “World”;
Conditionals • Just like C and Java … CAKE$condition = true; if($condition && 1 == 1) { echo “Whoohoo”; } else { echo “How did this happen?”; }
Arrays $numbers = array(); $numbers[] = 1; // pushes integer 1 onto array $numbers[] = 2; // pushes integer 2 onto array sizeof($myArray); // returns length of array print_r($myArray); // prints the array for you
Loops • Same for loop as before (while loops work too! WOW!) • Introducing the for each loop: foreach($numbers as $number) { echo “My number is ” . $number; }
Some Coding Hints • Modulus • $i % 10 == 0 if $i is divisible by 10 • $isEven = ($i % 2 == 0); • $isEven = !($i%2); // same thing but shorter • Ternary Operators • echo isEven ? “It’s Even!” : “It’s Not”;