|
| 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. |
0 commit comments