https://www.codecademy.com/en/tracks/php
Выполняется на сервере, в отличие от JavaScript. Файлы - с расширением .php.
Your PHP code goes inside the <?php and ?> delimiters. Here we use the function echo to output I'm learning PHP!. We also end the line with a semicolon.
The echo function outputs strings.
<?php echo "I'm learning PHP!"; ?>
Сoncatenation operator glues several strings together. The concatenation operator is just a dot (.).
<?php echo "Hello," . " " . "world" . "!"; ?>
In addition to outputting strings, PHP can also do math. Remember: no quotes around numbers!
<?php echo 5 * 7; ?>
A variable can store a string or a number, and gives it a specific case-senstive name. All variable names in PHP start with a dollar sign ( $ ).
<?php $myName = "Beyonce"; $myAge = 32; echo "$myName<br />"; echo "$myAge"; ?>
Comments use two forward slashes (//)
<?php echo "I get printed!"; // I don't! I'm a comment. ?>
> Greater than
< Less than
<= Less than or equal to
>= Greater than or equal to
== Equal to
!= Not equal to
An if statement is made up of the if keyword, a condition like we've seen before, and a pair of curly braces { }. If the answer to the condition is yes, the code inside the curly braces will run.
<?php $age = 17; if( $age > 16 ) { echo "You can drive!"; } ?>
In addition to doing something when the condition is true, we can do something else if the condition is false. We can do this using an if/else statement:
<?php $name = "Edgar"; if ($name == "Simon") { print "I know you!"; } else { print "Who are you?"; } ?>
Elseif - it extends an if statement to execute a different statement in case the original if expression evaluates to FALSE. However, unlike else, it will execute that alternative expression only if the elseif conditional expression evaluates to TRUE.
<?php $z = 2 + 3; // будет выведено слово "close" if ($z == 4) { echo "right"; } elseif ($z == 5) { echo "close"; } else { echo "wrong"; } ?>
A switch statement comes in handy when you have a series of if/elseif/else statements with multiple expressions that depend on the same value. The switch statement also provides a bit of efficiency and readability. Switches work like if statements, if a condition is true, it executes a block of code.
$myNum = 2; switch ($myNum) { case 1: echo "1"; break; case 2: echo "2"; break; case 3: echo "3"; break; default: echo "None of the above"; }
You sometimes want to make multiple expressions, all of which have the same result. Consider the following if statement:
if ($i == 1 || $i == 2 || $i == 3) { echo '$i is somewhere between 1 and 3.'; }
With a switch statement, you can do this by adding cases right after another without a break. This is called falling through. The following code works exactly like the above if statement:
case 1: case 2: case 3: echo '$i is somewhere between 1 and 3.'; break;
There's no difference when using either the curly brace syntax (first example) or alternative syntax (second example), it only provides readability, thus it's usually used when mixing HTML and PHP code in the same file.
switch ($i) { }
switch ($i): endswitch;
An array is a list of items, a bit like a shopping list. It allows you to store more than one item in only one variable. An array starts in the same way as a variable, with the $ sign, and then a name, followed by =. However, this is when things start to get different. When declaring an array, we have to use array().
<?php $array = array("Egg", "Tomato", "Beans", "Chips", "Sausage" ); ?>
Each item in an array is numbered starting from 0. We can access a particular item of the array using its position.
<?php $myArray = array("do", "re", "mi"); echo $myArray[0] // outputs "do" ?>
When accessing arrays by offset, you can actually use two different types of syntax: the [ ] syntax we've covered, or you can use curly braces ({ }). You use the curly braces just like you use the square brackets:
<?php $myArray = array("do", "re", "mi"); print $myArray{2}; // prints "mi"; ?>
An item in an array can be changed by specifying its position and providing a new value.
<?php $myArray = array("red", "blue", "yellow"); echo $myArray[1]; // outputs "blue" $myArray[1] = "green"; echo $myArray[1]; // outputs "green" ?>
Finally, you can remove elements using unset:
<?php $array = array("red", "blue", "green"); unset($array[2]); ?>
You can even delete the whole array:
<?php unset($array); ?>
A loop is a useful bit of code that repeats a series of instructions for you.
For loops are great for running the same code over and over, especially when you know ahead of time how many times you'll need to loop.
Instead of using echo (list of leap years)
<?php echo 2004; echo 2008; echo 2012; // And so on ?>
we can use
<?php for ($leap = 2004; $leap < 2050; $leap = $leap + 4) { echo "<p>$leap</p>"; } ?>
$i++ is shorthand for $i = $i + 1. You'll see this a lot!
<?php for ($i = 0; $i < 10; $i++) { echo $i; } // echoes 0123456789 ?>
The foreach loop is used to iterate over each element of an object—which makes it perfect for use with arrays! You can think of foreach as jumping from element to element in the array and running the code between { }s for each of those elements.
<?php $langs = array("JavaScript", "HTML/CSS", "PHP", "Python", "Ruby"); // Between the parentheses, we use the $langs as $lang) syntax to tell PHP: // "For each thing in $langs, assign that thing temporarily to the variable $lang." foreach ($langs as $lang) { echo "<li>$lang</li>"; } unset($lang); ?>
A for loop can allow for a set number of loop iterations. But what about a situation where (due to randomness, perhaps) you don't know how many times the loop should repeat? In that case, you can use a while loop. A while loop will execute as long as a certain condition is true.
<?php //Вывод чисел от 1 до 10 $kk = 1; while ($kk <= 10) { echo "$kk<br>"; $kk ++; } ?>
It is important when writing loops to make sure that the loop will exit at some point. The following loop will never exit and is an example of an infinite loop.
while(2 > 1){ // Code }
Avoid infinite loops like the plague!
PHP offers the following alternative syntax for while loops:
while(cond): // looped statements go here endwhile;
When they are embedded in HTML, loops that use this endwhile syntax can be more readable than the equivalent syntax involving curly braces.
A while loop checks the loop condition before each iteration of the code inside. A do/while loop checks the condition after each iteration before looping back. One consequence of this difference is that the code inside a while loop can be bypassed entirely whereas the code inside a do/while loop will execute at least once.
This means that the loop condition can depend exclusively on code within the loop's body. This is the case for the code in the editor where each iteration represents a coin flip, and any time the result of the coin flip is tails, the loop stops.
Тут я ни хрена не понимаю.
<?php // keep flipping a coin // as long as the result is heads! $flipCount = 0; do { $flip = rand(0,1); $flipCount ++; if ($flip){ echo "<div class=\"coin\">H</div>"; } else { echo "<div class=\"coin\">T</div>"; } } while ($flip); $verb = "were"; $last = "flips"; if ($flipCount == 1) { $verb = "was"; $last = "flip"; } echo "<p>There {$verb} {$flipCount} {$last}!</p>"; ?> </php>
.css:
.coin { height: 50px; width: 50px; border-radius: 25px; background-color: gray; text-align: center; font-weight: bold; font-family: sans-serif; color: white; margin: 10px; display: inline-block; line-height: 50px; font-size: 20px; }
Functions are reusable pieces of code that you can use throughout an application, saving you lots of copying and pasting. PHP has lots of built-in functions, and we'll learn some of them in these exercises. The first set of functions we'll learn about are string manipulation functions.
strlen() is one of the most common String functions in PHP. You pass it a string, or variable containing a string, and it returns the number of characters in that string.
<?php // выведет цифру 5 $length = strlen("david"); print $length; ?>
substr() allows you to return a substring (piece of) of your string. You pass this function the string you want to get a substring of, the character in your string to start at, and how many characters you want after your starting point.
Two other very useful string functions are strtoupper() and strtolower(), which make your entire string UPPERCASE or lowercase.
<?php $n="SuperCalifragilisticExpialidocious"; $p=substr($n, 0, 5); // Выведет Super echo "$p<br />"; $p2=substr($n, 5, 15); // Выведет Califragilistic echo "$p2<br />"; $u=strtoupper($p); // Выведет SUPER echo $u $l=strtolower($p2); // Выведет califragilistic echo $l ?>
strpos() find the position of the first occurrence of a substring in a string.
strpos("emily", "e"); // 0 strpos("emily", "i"); // 2 strpos("emily", "ily"); // 2 strpos("emily", "zxc"); // false
It returns either the index of the first character, or false if nothing can be found.
if (strpos("david","h") === false) { print "Sorry, no 'h' in 'david'"; } // prints the "Sorry" message
The most common Math function you'll use is round(). This function rounds floating point numbers (numbers with decimal points in them) up or down. You can use round() to round your number to an integer, or to round off complex floating point numbers to a specific number of decimal places. This is accomplished by passing a second, optional parameter to round(), telling it how many decimal places you want the number rounded to.
// Round pi down from 3.1416... $round = round(M_PI); // M_PI is a PHP constant that is equal to pi. print $round; // prints 3 // This time, round pi to 4 places $round_decimal = round(M_PI, 4); print $round_decimal; // prints 3.1416
A very common and useful function is rand(). This function returns a random number between two numbers. Optionally, you can provide your min and max numbers as parameters.
// prints a number between 0 and 32767 print rand(); // prints a number between 1 and 10 print rand(1,10);
Дали задание; несмотря на подсказки, сделать не смог, результат тупо нашёл в интернете, причём не уверен, что именно так нужно было сделать. Не понимаю взаимодействия чисел, которыми оперирует rand, и букв в исходной строке. Вообще ничего не понимаю.
Create a new variable $name and store your name in it. Then print a random character from your name. Use your knowledge of strlen(string), rand(min, max), and substr(string, start, length) to do this.
HINT: Remember that substr() treats characters in a string as a zero-indexed array (first letter is at position zero). This means that the last character in the string will be at position length - 1. Remember that rand() accepts 2 arguments: min and max. The last character in your name is at position strlen($name) - 1. Remember that substr() accepts 3 arguments: string, starting position, and number of characters to return.
<?php // Use your knowledge of strlen(), substr(), and rand() to // print a random character from your name to the screen. $name="Viacheslav"; $rl = $name[rand(0, strlen($name)-1)]; echo $rl; ?>
Arrays are a very common thing to use in programming. In fact, array() is actually a function! Good job, you have already used an array function. Aside from the array() function itself, array_push() is arguably the most common and useful function for manipulating arrays. array_push() takes two arguments: an array, and an element to add to the end of that array.
Another cool array function is count(). Passing an array to count() will return the number of elements in that array.
<?php $a=array(); array_push($a, "First"); array_push($a, "Second"); array_push($a, "Third"); array_push($a, "Fourth"); array_push($a, "Fifth"); array_push($a, "Sixth"); foreach ($a as $m) { echo "$m<br />"; } echo "There are " . count($a) . " elements overall"; ?>
Задание: выбрать из упорядоченного по алфавиту списка одно имя случайным образом и вывести его большими буквами.
<?php // Создать массив и засунуть туда имена $a=array(); array_push($a, "Vasya"); array_push($a, "Petya"); array_push($a, "Kolya"); array_push($a, "Sveta"); array_push($a, "Olya"); array_push($a, "Masha"); array_push($a, "Natasha"); array_push($a, "Lena"); array_push($a, "Julya"); array_push($a, "Lesha"); // Сортировка sort($a); // Извлечь из массива одно значение, которое будет случайным $w=$a[rand(0, count($a) - 1)]; //Вывести капсом echo strtoupper($w); ?>
The typical structure of a function is as follows:
function name(parameters) { statement; } // Пример // Here we define the function... function helloWorld() { echo "Hello world!"; } // ...and here we call it! helloWorld();
Instead of printing something to the screen, what if you want to make it the value that the function outputs so it can be used elsewhere in your program? In PHP, the return keyword does just that. It returns to us a value that we can work with. The difference between this and echo or print is that it doesn't actually display the value.
Think of it like a calculator solving a mathematical problem that takes several steps to complete. The value from each step is computed, but we don't see the result until we get the final answer. In other words, each value is returned and the final answer is echoed on screen for us.
Functions wouldn't be nearly as useful if they weren't able to take in some input. This is where parameters or arguments come in. These are the variables or inputs that a function uses to perform calculations.
function squareValue($number) { echo $number * $number; } $n = 6; squareValue($n); // echos 36
The function squareValue, above, takes one parameter, which it multiplies by itself and then echos the result. The names of the parameters themselves are used internally within the function, so they should be named something helpful.
You can also use multiple parameters as long as they are separated by commas.
PHP is an object-oriented programming language, which means that you can create objects, which can contain variables and functions.
When talking about objects, you refer to variables belonging to these objects as properties (or attributes or fields), and functions are called methods.
These objects are essential when dealing with PHP, as almost everything is an object: for example, functions or arrays are objects, too! And this shows why we use objects: we can bundle our functions and data in one place, we can create objects easily using classes (object constructors), so we can create lots of instances (objects, which have been constructed via a class), which contain mostly the same data, except some little nuances.
There is a Person class and one instance stored in $me on line 32. Then the greet() method of the $me object is called and the result is echod on line 35. Then the stylesheet adds some color to the result.
Try to understand the code. (Don't worry if some of it is tricky — we'll go over it!)
<?php // The code below creates the class class Person { // Creating some properties (variables tied to an object) public $isAlive = true; public $firstname; public $lastname; public $age; // Assigning the values public function __construct($firstname, $lastname, $age) { $this->firstname = $firstname; $this->lastname = $lastname; $this->age = $age; } // Creating a method (function tied to an object) public function greet() { return "Hello, my name is " . $this->firstname . " " . $this->lastname . ". Nice to meet you! :-)"; } } // Creating a new person called "boring 12345", who is 12345 years old ;-) $me = new Person('boring', '12345', 12345); // Printing out, what the greet method returns echo $me->greet(); ?>
How object-oriented programming is used in real life can be shown with a forum as an example:
Every forum user (object) has the same rights: he can log in and write (methods), can contain some settings (properties), but every user has a different name (another property).
Every user is created easily, as you create a new instance of a User class when you sign up. And as we've seen, there are some properties and methods that every instance has in common (such as logging in and writing), and there are some which are unique (such as each user's name).
And without object-oriented programming—OOP for short—this could not be done that easily.
Another example: on the above, there is a Person class, so every new Person has some properties, like $isAlive or $firstname, and a method greet().
Right now there is only one instance of the Person class: $me. But we'll reconstruct this class and you'll even create another instance of the class, so your name will be echod, too.
In the next exercises we are going to create some classes, so let's start coding.
Great, now you know the technical terms. Let's start coding by reconstructing the Person class.
The basic class syntax looks like the following:
class Classname { }
The class keyword means that you create a new class; the syntax is quite similar to the function syntax.
And you can create new instances of this class using the following syntax:
$obj1 = new Classname();
The new keyword means that you create a new object and ensures that your arguments are added as properties, so it initializes the constructor (which we are going to deal with later).
We don't need to pass in any arguments, as we haven't added any properties (which can store different values depending on the instance) quite yet.