<h1>Intro to <?php echo "PHP"; ?></h1>
Rasmus Lerdorf first conceived of PHP in 1994
<?php $integer = 1; $float = 1.5; echo $integer + $float; // 2.5 <- float $string = 'foo'; echo $string . $integer; // 'foo1' <- concatenation ?>
<?php $list = array('foo', 'bar', 'bar2'); echo $list[1]; // 'bar' $list[] = 'foo2'; echo $list[3]; // 'foo2' $array = array('f' => 'foo', 'b' => 'bar'); echo $array['f']; // 'foo' ?>
Write a script to caclculate 13! = factorial(13)
php factor.php 6227020800
X <- "READ FROM INPUT" IF X < 10 THEN echo X ELSE IF X < 20 THEN echo X * X ELSE echo factor(X)
<?php // $i = 10; if (/* $i == 0 */) { // echo 'Zero'; } elseif (/* $i <= 10 */) { // echo 'Small'; } else { // echo 'Big'; } // TIP: "if + TAB" ?>
<?php // $i = 0; while (/* $i < 10 */) { // echo $i; // $i = $i + 1; } // TIP: "while + TAB" ?>
<?php for (/* $i=0; $i < 10; $i++ */) { // echo $i; } // TIP: "for + TAB" ?>
<?php // $array = array('bob', 'jules', 'mark'); foreach (/* $array as $element */) { // echo $element; } // TIP: "foreach + TAB" ?>
php factor.php 6227020800
<?php function FunctionName($var1, $var2) { // code... return $var1 + $var2; } echo FunctionName(1, 2); // 3 // TIP: "fun + TAB" ?>
Create a new file
php factor_function.php 6227020800
<?php function factor($n) { // code... return $something; } echo factor(13); // 6227020800 ?>
<?php function factorRec($n) { if ($n == 1) { return 1; } else { return $n * factorRec($n - 1); } // return $n > 1 ? $n * factorRec($n - 1) : $n; } echo factorRec(13); // 6227020800 ?>
Create a new file
php fibo.php 233
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Homepage</title> </head> <body> <h1>Awesome homepage</h1> <p>First paragraph</p> <a href="/factor.php">Surprise!</a> </body> </html>Create a file index.html at the root of your workspace Preview it
<input name="mynumber" />
Value: Submit
<form action="/post.php" method="POST">; <label>Value:</label> <input name="mynumber" /> <button type="submit">Submit</button> </form>
Good news: this data is fetchable with PHP!
<?php echo $_POST["mynumber"]; ?>Create a file post.php at the root of your workspace Refresh index.html in the preview Fill the form, and submit it...
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Result</title> </head> <body> <h2>Your result is <b><?php echo $_POST["mynumber"]; ?></b></h2> </body> </html>Updatepost.php Refresh index.html in the preview Fill the form, and submit it...
Update your post.php file to apply the factorial function on the input, and display it