Skip to content

Commit aa131f6

Browse files
Merge pull request #428 from kodikos/php-tutorial-2
PHP Tutorial lesson 2
2 parents 903a3d0 + f7472c1 commit aa131f6

File tree

4 files changed

+318
-8
lines changed

4 files changed

+318
-8
lines changed

index.html

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -97,10 +97,12 @@ <h2>iOS</h2>
9797
</ul>
9898

9999
<h2>PHP</h2>
100-
<p class="lead">If you are just getting started quickly and easily with PHP, we recommend using <a href="https://docs.c9.io/docs/getting-started">Cloud9</a>, as setting up your local environment can be time consuming.</p>
100+
<p class="lead">Getting your PHP environment set up can be complicated. We've summarized the
101+
simplest solutions in our <a href="php/using-php/simple.html">simple guide to using PHP</a></p>
101102

102103
<ul>
103104
<li><a href="php/lesson1/tutorial.html">Lesson 1 - Introduction to PHP</a></li>
105+
<li><a href="php/lesson2/tutorial.html">Lesson 2 - Values and Variables</a></li>
104106
</ul>
105107

106108
<h2>Command Line</h2>

php/lesson1/tutorial.md

Lines changed: 2 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -6,9 +6,7 @@ title: Introduction to PHP
66
##### Requirements
77

88
* 15 minutes
9-
* PHP installed - this is by default on most Operating Systems. But if not, here are the official [installation instructions](http://php.net/manual/en/install.php)
10-
* Check installation by running the following command in cli `php -v`, this should output the version, eg. **5.5.9**
11-
* Or use an [online IDE](https://docs.c9.io/docs/getting-started)
9+
* PHP installed - PHP comes packaged in various ways. Please use our [installation guide](../using-php/simple.html) for an in-depth guide to the options. This tutorial assumes you have installed the command-line version. If you use other methods, you may not need to start the PHP WebServer.
1210

1311
##### Achievements
1412

@@ -53,15 +51,12 @@ On the Command Line (CLI), type:
5351
php index.php
5452
```
5553

56-
And the output will be:
54+
And the output that displays just below where you typed will be:
5755

5856
```bash
59-
$ php index.php
6057
Hello World
6158
```
6259

63-
*Note: `$` implies the Command Line shell, you did not need to type this.*
64-
6560
## How to the output in the browser?
6661

6762
Seeing it on the Command Line is great, but what about the browser? We will need to get a WebServer running, the easiest way is to use the built-in PHP WebServer.

php/lesson2/tutorial.md

Lines changed: 229 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,229 @@
1+
---
2+
layout: page
3+
title: PHP Tutorial 2
4+
---
5+
6+
##### Requirements
7+
8+
* PHP Installation with command-line (use our [guide](../using-php/simple.html) for help on this)
9+
10+
* That you have taken one of the other programming language courses, like the Javascript, Ruby or Python courses so that you are familiar with some of the typical things you see in computer languages.
11+
12+
##### Achievements
13+
14+
You will explore types of values, variables and some simple expressions and lexical features in PHP.
15+
16+
---
17+
18+
## Using Interactive PHP mode
19+
20+
For this tutorial, we will be using the interactive mode of the PHP command-line (CLI). Please see our [guide](../using-php/simple.html#interactive-mode) for more information about using this mode.
21+
22+
23+
#### Comments
24+
25+
Let's try doing nothing. You can add comments in three ways:
26+
```php
27+
// Comment style 1 - anything after the double slash to the end of the line is ignored
28+
# Comment style 2 - anything after the hash sign to the end of the line is ignored
29+
/* Comment style 3 - anything to the next star and slash are ignored, can be in the middle of a
30+
line, or be several lines long */
31+
```
32+
Try these out and see absolutely nothing happen! We'll be using these on the end of our example lines to explain them and what you might see as output. You *don't* have to type out comments.
33+
34+
35+
## Simple Values
36+
37+
#### Numbers
38+
39+
PHP can store numbers as _integers_ (whole numbers) and _floating-point_ (numbers with a fractional part). Try typing:
40+
```php
41+
echo 3;
42+
echo 4.1;
43+
```
44+
This should display the number `3` and number `4.1` respectively. We can do calculations as well:
45+
```php
46+
echo 3 + 5; // displays 8
47+
echo 2 - 0.3; // displays 1.7
48+
echo 2 * 5; // displays 10
49+
echo 1 / 4; // displays 0.25
50+
echo 6 % 5; // displays 1 (modulus, or the remainder of a division)
51+
echo 22 / 7; // displays 3.1428571428571
52+
```
53+
Technically the last calculation should have more digits, but the default storage space only stores this many digits. This is called its' _precision_.
54+
55+
PHP has a [maths library](https://secure.php.net/manual/en/ref.math.php). We'll cover functions in more detail later, but here are some simple examples:
56+
```php
57+
echo floor(4.7); // displays the number rounded down to the nearest whole, should be 4
58+
echo round(4.5); // displays the whole number nearest to the fraction, should be 5
59+
```
60+
61+
#### Strings
62+
63+
String represent text.
64+
```php
65+
echo "I'm a little teapot";
66+
```
67+
You can use double or single quotes to wrap strings, but they behave slightly differently. The single quote is more _literal_:
68+
```php
69+
echo "This will display \n on 2 lines";
70+
echo 'This will not display \n on 2 lines';
71+
```
72+
The `\` indicates an escape sequence is about to follow. Escaping allows you to access special characters. `\n` means newline.
73+
74+
You can join strings together in php using a period `.`, e.g.:
75+
```php
76+
echo "Let's all " . "join together!";
77+
```
78+
79+
Like the maths library for numbers, PHP has a [string library](https://secure.php.net/manual/en/ref.strings.php) for having fun with strings. Here are a few simple examples:
80+
```php
81+
echo substr("bit of a string", 0, 3); // displays bit
82+
echo trim(" no space at the inn "); // displays no space at the inn
83+
echo stripslashes('no\nslopes'); // displays nonslopes
84+
echo strpos("where dat?", "dat"); // displays 6
85+
echo str_repeat("badger ", 1000); // you get the idea!
86+
echo str_replace("Love", "<3", "Love coding"); // displays <3 coding
87+
```
88+
89+
#### Booleans
90+
91+
Booleans represent true or false. When you do conditional tests in your code, they end up as a boolean.
92+
```php
93+
echo true; // displays 1
94+
echo false; // displays false... wut?
95+
```
96+
As you can see, it's not as straightforward as all that. What's going on here is that `true` is represented as the number `1` when outputted as a string, but false is outputted as nothing. To see these properly, it's worth introducing you to a handy debugging function, `var_dump`:
97+
```php
98+
var_dump(true); // displays bool(true)
99+
var_dump(false); // displays bool(false)
100+
```
101+
`var_dump` returns more information about a value or variable, including its' type.
102+
103+
#### Arrays
104+
105+
Want to store a list of things? Let's use an array:
106+
```php
107+
echo [4, 5, 6];
108+
```
109+
This will output:
110+
```
111+
PHP Notice: Array to string conversion in php shell code on line 1
112+
Array
113+
```
114+
Err, wasn't expecting that? The PHP echo command has to convert values to strings to display them. Most of the time it knows what to do, but it doesn't like to second guess you so wants you to be more specific. So actually it's outputted the string `Array` and warned you with the `PHP Notice` line why it's not what you expected. We can use a `var_dump`, or a string function that can tell it how to format the array items. Here's an example:
115+
```php
116+
echo join(", ", [4, 5, 6]);
117+
```
118+
This tells it to join each element in the array together with a comma, so the output becomes:
119+
```
120+
4, 5, 6
121+
```
122+
You don't have to have items of just one type in an array, you can mix them up. E.g:
123+
```php
124+
echo join(", ", ["odd", "squad", 4, true]); // displays odd, squad, 4, 1
125+
```
126+
127+
#### Associative Arrays
128+
129+
Arrays in PHP also double as _hashes_ or _maps_. This means you can name the way refer to values in the array, using a _key_. We'll switch back to using `var_dump` as echo won't show the keys:
130+
```php
131+
var_dump(["fred" => 43, "barney" => 34]);
132+
```
133+
Will output:
134+
```
135+
array(1) {
136+
'fred' =>
137+
int(43)
138+
'barney' =>
139+
int(34)
140+
}
141+
```
142+
We'll revisit arrays further down to see how you recall individual values from them.
143+
144+
Arrays have their own set of [array functions](https://secure.php.net/manual/en/ref.array.php)
145+
146+
#### Nothing
147+
148+
There is another value to be aware of, that of `NULL`. We'll have to use var_dump again to see this;
149+
```php
150+
var_dump(null); // displays NULL
151+
```
152+
Wow, that was worth it! `NULL` is a special keyword of PHP to represent a purposeful non-present value, so that it doesn't get mixed up with an empty string `""` or the value 0. It's a bit more useful in conditions.
153+
154+
155+
## Variables
156+
157+
PHP can store information for retrieval elsewhere, in variables. They can store numbers, strings, arrays, objects, and special resource handlers (such as a file or network handler). All variables start with a `$` followed by at least 1 letter of the alphabet, followed by combination of letters and numbers to make up the name, e.g. `$name`, `$emailAddress`, `$address2`. It can also include underscores, e.g. `$under_score`. Let's try putting some stuff in variables!
158+
```php
159+
$num = 4;
160+
echo $num; // displays 4
161+
```
162+
```php
163+
$str = "nice pizza!";
164+
echo $str; // displays nice pizza!
165+
```
166+
```php
167+
$calc = 1.2 + 3.4;
168+
echo $calc; // displays 4.6
169+
```
170+
```php
171+
$bit_of_pizza = substr($str, 5);
172+
echo str_repeat($bit_of_pizza, 3); // displays pizza! pizza! pizza!
173+
```
174+
175+
### Arrays (slight return)
176+
177+
Remember those arrays we looked at? It's a bit easier to see how we access elements from them if we put them in variables:
178+
```php
179+
$nums = [4, 5, 6];
180+
echo $nums[1]; // displays 5
181+
```
182+
Expecting the first item to be 4? Array items start from 0, so `$nums[1]` refers to the 2nd item in the array.
183+
184+
Another feature with arrays is the ability to alter them. E.g.
185+
```php
186+
$nums[1] = 3;
187+
echo $nums[1]; // displays 3
188+
```
189+
190+
Here's a convenient way to add another item to the array:
191+
```php
192+
$nums[] = 7;
193+
echo join(", ", $nums); // displays 4, 3, 6, 7
194+
```
195+
Let's revisit associative arrays and show how to access items in these:
196+
```php
197+
$cartoon_ages = ["Fred" => 43, "Barney" => 34];
198+
echo $cartoon_ages["Fred"]; // displays 43
199+
```
200+
Again, you can add more entries to this array:
201+
```php
202+
$cartoon_ages["Betty"] = 30;
203+
```
204+
If the key `Betty` already existed, it would overwrite the value with the new one that you set.
205+
206+
You may be wondering with arrays whether you can mix normal arrays with associative arrays? Why not?! Well, yes you can! Let the madness ensue!
207+
```php
208+
$allIn = [4, 5, "here" => "for", 20 => "some reason"];
209+
var_dump($allIn);
210+
```
211+
Will output:
212+
```
213+
array(4) {
214+
[0] =>
215+
int(4)
216+
[1] =>
217+
int(5)
218+
'here' =>
219+
string(3) "for"
220+
[20] =>
221+
string(11) "some reason"
222+
}
223+
```
224+
Yes, you can even write integers as keys to truly upset the keys in the array!
225+
226+
227+
## Summary
228+
229+
In this tutorial, you have gone through the basic types of values in PHP, and how they can stored in variables and then retrieved from them.

php/using-php/simple.md

Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
---
2+
layout: page
3+
title: Running PHP - A Simple Guide
4+
---
5+
6+
## Introduction
7+
8+
This page is to help with getting set up easily with PHP.
9+
10+
PHP has two main ways of operating - as a command-line tool (CLI), or as part of a web server. The command-line version is useful for doing data processing and other background tasks. When integrated with a web server it is able to create dynamic web pages by allowing you to modify the HTML that is delivered to a user.
11+
12+
13+
## Online
14+
15+
You should be able to try out most things in the PHP tutorials with any online PHP tool. Some are limited by whether you have full control of the HTML, or whether other features are available, like a filesystem or database.
16+
17+
### Using PHPFiddle
18+
19+
[PHPFiddle.org](https://phpfiddle.org/) is a simple and well featured way to try out PHP. It is able to serve a full web page, and even provides MySQL database access if you set up a login.
20+
21+
22+
## Installing on your machine
23+
24+
Giving you the most flexible options for developing with PHP, and is the way we will assume in the guides.
25+
26+
### Do you already have it installed?
27+
28+
You never know, PHP may be already installed on your system! You can check by going to a command-line and typing:
29+
```
30+
php -v
31+
```
32+
This will indicate if the PHP command-line version is installed. If you are running a local web server, you could try putting a file (with `.php` on the end of the filename) into the web folder that contains the following:
33+
```
34+
<?php
35+
echo phpinfo();
36+
```
37+
When you access that file via your web browser, it should return a page giving lots of information about the PHP configuration, this will mean your web server is PHP-enabled.
38+
39+
40+
### Installing PHP
41+
42+
Installing just the PHP command-line is fairly straight-forward. You can follow their [official guide](https://secure.php.net/manual/en/install.php) for your operating system. Uninstalling is typically just a case of deleting the folder into which it was installed.
43+
44+
45+
46+
### Using PHP
47+
48+
#### Script mode
49+
50+
This is the typical way of running a PHP on the command-line, as a script. You write your PHP in a file typically ending with the `.php` extension. You then call PHP like any other application like this:
51+
```
52+
php script.php
53+
```
54+
The output you will see are anything that you `echo` or `print`, or errors that have occured whilst trying to process your script.
55+
56+
57+
#### Interactive mode
58+
59+
Some tutorials advise using the interactive mode of the PHP command-line (CLI). To start this, at a terminal on your machine type:
60+
```bash
61+
php -a
62+
```
63+
You can exit interactive mode by typing `quit` or `exit` and ENTER.
64+
65+
Unlike other language interactive modes like Javascript or Ruby, PHP is always in _command_ mode. So when you type in commands to the PHP interpreter, it will display nothing if you only enter an expression (e.g. `3 + 2;`). So we typically add the keyword `echo` in front to tell it to display the value of the expression, e.g. `echo 3 + 2;`. We will indicate when to use echo in our examples.
66+
67+
PHP interactive mode also displays extra information which other modes of operation in PHP don't. Because of this, examples of output may remove these from the output. Don't worry, these can generally be ignored, We're trying to draw your attention to the important things that PHP is doing.
68+
69+
70+
#### Server mode
71+
72+
In some tutorials we will be building web pages/sites with PHP. We will use the built-in server mode for this.
73+
74+
*Note: The built-in PHP WebServer is great for development, but **NOT** production.* See the advanced setups section below for more information about this.
75+
76+
Go to the directory where you created the _index.php_ file and run the following command:
77+
78+
```bash
79+
$ php -S 0.0.0.0:8080
80+
```
81+
* `php` is the same command from before, that we used to run our **php** script
82+
* `-S` means built-in WebServer
83+
* `0.0.0.0` is the IP that the WebServer should listen on. By using `0` it will listen on everything - fine for development
84+
* `:8080` sets the port to listen on - fine for development but in production the default port is `80` and therefore not required when accessing a URL. The colon character is used after a hostname or IP address to indicate that you wish to specify the port number on that host

0 commit comments

Comments
 (0)