Hello, World!
PHP is the most commonly used programming language for the web today. PHP is very common because it has a relatively simple architecture compared to other MVC based web frameworks (Python, Ruby, node.js, etc).
Unlike the standard web frameworks, a PHP file is actually an "enhanced" HTML file, which is also capable of executing code inside a document. So for example, you may start with a simple HTML page which looks like this:
Example:-
Hello!
And later on add a PHP section which executes PHP code, and writes the output as HTML. Notice that the PHP line disappeared when executing, since the PHP code is replaced by the output.
Let's try adding the name of the user's name.
Hello !
On this tutorial however, we will focus on learning PHP as a programming language and not web development. Therefore, we will not use HTML at all, and focus on writing code as opposed to rendering web pages.
In our tutorials, we will always open and close a PHP tag (starting with and ending with ?>) in the beginning and the end of our code.
For testing our code, we are able to print messages to our console using the echo command.
Variables and Types
To define a variable, simply use the following syntax:
$x = 1;
$y = "foo";
$z = True;
We have just defined a variable named x with the number 1, a variable named y with the string "foo" and a variable name z with the boolean value True. Once they are defined, we can use them in the code.
PHP has many types of variables, but the most basic variable types are integer (whole numbers), float (real numbers), strings, and booleans.
PHP also has arrays and objects which we will explain in other tutorials.
Variables can also be set to NULL, which means that the variables exist, but do not contain any value.
Operators
We can use simple arithmetic operators to add, subtract or concatenate between variables.
We can also print out PHP variables using the echo command (you can try it out now).
For example, let's sum up two numbers, put the result in a new variable, and print out the result.
$x = 1;
$y = 2;
$sum = $x + $y;
echo $sum; // prints out 3
String formatting
Like Perl, PHP double quoted strings can format strings using defined variables. For example:
$name = "Jake";
echo "Your name is $name"; // prints out Your name is Jake
Exercise
Part 1
Define the variables name and age so that a line would be printed out saying the following sentence:
Hello Jake. You are 20 years old.
Notice that the code contains a special character sequence at the end called a newline - \n. This sequence will cause the next line printed out to be printed out on the next line. For web development, this is not important, since we use HTML tags for this purpose.
Part 2
Sum up the variables x and y and put the result in the sum variable.
_________________________________________________________________________________
Simple arrays
Arrays are a special type of variable that can contain many variables, and hold them in a list.
For example, let's say we want to create a list of all the odd numbers between 1 and 10. Once we create the list, we can assign new variables that will refer to a variable in the array, using the index of the variable.
To use the first variable in the list (in this case the number 1), we will need to give the first index, which is 0, since PHP uses zero based indices, like almost all programming languages today.
$odd_numbers = [1,3,5,7,9];
$first_odd_number = $odd_numbers[0];
$second_odd_number = $odd_numbers[1];
echo "The first odd number is $first_odd_number\n";
echo "The second odd number is $second_odd_number\n";
We can now add new variables using an index. To add an item to the end of the list, we can assign the array with index 5 (the 6th variable):
$odd_numbers = [1,3,5,7,9];
$odd_numbers[5] = 11;
print_r($odd_numbers);
Arrays can contain different types of variables according to your needs, and can even contain other arrays or objects as members.
To delete an item from an array, use the unset function on the member itself. For example:
$odd_numbers = [1,3,5,7,9];
unset($odd_numbers[2]); // will remove the 3rd item (5) from the list
print_r($odd_numbers);
Useful functions
The count function returns the number of members an array has.
$odd_numbers = [1,3,5,7,9];
echo count($odd_numbers);
The reset function gets the first member of the array. (It also resets the internal iteration pointer).
$odd_numbers = [1,3,5,7,9];
$first_item = reset($odd_numbers);
echo $first_item;
We can also use the index syntax to get the first member of the array, as follows:
$odd_numbers = [1,3,5,7,9];
$first_item = $odd_numbers[0];
echo $first_item;
The end function gets the last member of the array
$odd_numbers = [1,3,5,7,9];
$last_item = end($odd_numbers);
echo $last_item;.
We can also use the count function to get the number of elements in the list, and then use it to refer to the last variable in the array. Note that we subtract one from the last index because indices are zero based in PHP, so we need to fix the fact that we don't count variable number zero.
$odd_numbers = [1,3,5,7,9];
$last_index = count($odd_numbers) - 1;
$last_item = $odd_numbers[$last_index];
echo $last_item;
Stack and queue functions
Arrays can be used as stacks and queues as well.
To push a member to the end of an array, use the array_push function:
$numbers = [1,2,3];
array_push($numbers, 4); // now array is [1,2,3,4];
// print the new array
print_r($numbers);
To pop a member from the end of an array, use the array_pop function:
$numbers = [1,2,3,4];
array_pop($numbers); // now array is [1,2,3];
// print the new array
print_r($numbers);
To pop a member from the beginning of an array, use the array_shift function:
$numbers = [0,1,2,3];
array_shift($numbers); // now array is [1,2,3];
// print the new array
print_r($numbers);
Concatenating arrays
We can use the array_merge to concatenate between two arrays:
$odd_numbers = [1,3,5,7,9];
$even_numbers = [2,4,6,8,10];
$all_numbers = array_merge($odd_numbers, $even_numbers);
print_r($all_numbers);
Sorting arrays
We can use the sort function to sort arrays. The rsort function sorts arrays in reverse. Notice that sorting is done on the input array and does not return a new array.
$numbers = [4,2,3,1,5];
sort($numbers);
print_r($numbers);
Advanced array functions
The array_slice function returns a new array that contains a certain part of a specific array from an offset. For example, if we want to discard the first 3 elements of an array, we can do the following:
$numbers = [1,2,3,4,5,6];
print_r(array_slice($numbers, 3));
We can also decide to take a slide of a specific length. For example, if we want to take only two items, we can add another argument to the function:
$numbers = [1,2,3,4,5,6];
print_r(array_slice($numbers, 3, 2));
the array_splice function does exactly the same, however it will also remove the slice returned from the original array (in this case, the numbers variable).
$numbers = [1,2,3,4,5,6];
print_r(array_splice($numbers, 3, 2));
print_r($numbers);
Exercise
1. Create a new array which contains the even numbers 2,4,6,8 and 10. The name of the new array should be$even_numbers.
2. Concatenate the male_names and female_names arrays to create the names array.
_________________________________________________________________________________
Arrays with keys
PHP arrays are actually ordered maps, meaning that all values of arrays have keys, and the items inside the array preserve order. When using arrays as simple lists as we have seen last chapter, a zero based counter is used to set the keys. Each item which is added to the array increments the next index by 1.
A good example for using arrays with keys is a phone book. Let's say we want to save the phone numbers of people in a class.
$phone_numbers = [
"Alex" => "415-235-8573",
"Jessica" => "415-492-4856",
];
print_r($phone_numbers);
echo "Alex's phone number is " . $phone_numbers["Alex"] . "\n";
echo "Jessica's phone number is " . $phone_numbers["Jessica"] . "\n";
To add an item to an array using a key, we use the brackets operator, as you would expect.
$phone_numbers = [
"Alex" => "415-235-8573",
"Jessica" => "415-492-4856",
];
$phone_numbers["Michael"] = "415-955-3857";
print_r($phone_numbers);
To check if a key exists within an array, we can use the array_key_exists function:
$phone_numbers = [
"Alex" => "415-235-8573",
"Jessica" => "415-492-4856",
];
if (array_key_exists("Alex", $phone_numbers)) {
echo "Alex's phone number is " . $phone_numbers["Alex"] . "\n";
} else {
echo "Alex's phone number is not in the phone book!";
}
if (array_key_exists("Michael", $phone_numbers)) {
echo "Michael's phone number is " . $phone_numbers["Alex"] . "\n";
} else {
echo "Michael's phone number is not in the phone book!";
}
If we want to extract only the keys of the array (the names), we can use the array_keys function.
$phone_numbers = [
"Alex" => "415-235-8573",
"Jessica" => "415-492-4856",
];
print_r(array_keys($phone_numbers));
Alternatively, to get only the values of an array (the phone numbers), we can use the array_values function.
$phone_numbers = [
"Alex" => "415-235-8573",
"Jessica" => "415-492-4856",
];
print_r(array_values($phone_numbers));
Exercise
Add a number to the phone book for Eric, with the number 415-874-7659, either by adding it to the array definition, or as a separate code line.
0 comments:
Post a Comment