As the Topic Description says, this lesson really does build on your understanding of the first lesson (and to a certain extent the homework.) If you haven't already, I recommend you read through the first lesson, and at least read through the homework and answers.
Ok, so I'll break this into 4 sections, maths, string and number formatting, modifying string, and dates. Each one is fairly unique in itself, so I hope you enjoy!
Maths
______________________________________
Ok, so we all know that 1+1=2, but how do we program it? Well there are 5 math operators (yes 5 not 4). These are +-/* and %.
+ or the addition operator is pretty much self explanatory in what it does. As is -. generally you would use them like:
CODE
$variable = 2+2; // equals 4
or
$variable = $val1+$val2;
and subtraction:
$variable = 3.14159 - 9.51413; // equals -6.37254
or
$variable = $val1+$val2;
and subtraction:
$variable = 3.14159 - 9.51413; // equals -6.37254
The next two operators, / and * are division and multiplication respectively.
CODE
$x = 4*5*10; // equals 20
$y = $x/50; // equals 4
$y = $x/50; // equals 4
Like most simple maths equations, you can have as many terms as you want in the statement. In addition to this, php handles your order of operations normally:
CODE
$a = ((1+4)*5)/0.5; // equals 50.
Now, the almighty modulus operator, or %. This returns the remainder from the division of the two terms:
CODE
$remainder = 9%2; // $remainder will store the value (int) 1.
Now, to put all of these together:
CODE
$y = (3*3*3)/12 + 9%4; // which equals 4.
Now, there are a few maths functions which are very useful, these are:
sqrt($x); // returns the square root of $x
pow($x, $y); // returns $x to the power of $y
I wont mention all of them here, however there are other mathematical "functions" such as cos, sin, tan, floor, ceil and round - all of which are useful (especially if your doing geometrical work).
Math constants: These are preset values within PHP and can be used just like a variable ( however you call them without the the "$".
CODE
M_PI; // pi or 3.14159
M_E; // e or 2.718
M_E; // e or 2.718
There are many others, like specific approximations of Pi, and other static values that are commonly used.
So to use these constants in a line of code:
CODE
$Area = M_PI*pow($radius, 2); // returns the Area of the circle with a radius of $radius
Math and String formatting
______________________________________
To format a number, you use the number_format() function, which accepts a number and some formatting values ( such as commas and decimal points) and returns a string of the formatted number. Its 4 arguments are as follows:
number_format ($number, $number_of_decimals, $decimal_serperator, $thousands_seperator);
More complex number formatting can be
Which can be used like this:
CODE
format_number(104500.99, 2, ".", ","); // 104,500.99
More complex formatting of any string or number can be done by using printf() and sprintf(). The difference between the two is that sprintf() returns the value, but printf() displays the value.
Here's one I prepared earlier:
CODE
$money = sprintf("%05.2f", 123); //123.00
Here, % tells it to start parsing formatting. 0 is the padding, if the length of the number/string is shorter it is padded. After this I can add a "-", which tells it to pad on the left instead of the right which is default. Then comes a 5 or other digit which specifies the width of the number formatted. If its shorter than this number, then the padding is used. ".2" tells it to use 2 decimal points, and f says a float instead of s which is a string. I personally find that I don't have to use formatting much more complex than this - and if I do I can always look up the formatting reference on php.net
Manipulating strings
______________________________________
There is a myriad of string functions, so I cannot cover them all here. However there are a few very (very) useful ones that I often use regularly. The first is explode()!. This function takes 2 arguments, a string input, and a string delimiter. It returns an array of strings, that has been split at the delimiter (I'll be discussing Array's next week). eg:
CODE
$words = explode("This is a string!", " ");
will return:
"This", "is", "a", "string!". From this (and well cover the array functions next week) you could count the length of the array to find the number of words. Of course there is already a PHP function to count the words in a string, however you can already see a useful application of explode.
substr(), returns a sub string of the one passed into it. eg:
CODE
$word = substr("words are cool!", 0, 4); // "word"
Now this is probably a good time to explain string indexing. Most programming languages start counting at 0 and not 1. For this reason, the first character has the index of 0, the second character index 1, and so on so that the nth character has n-1 as its index
You can also use negative indexes. -1 refers to the last character, so substr("str" -1, 1); would return "r".
strlen("string");, very simple - returns the length of the string, in this case (int) 6.
Some functions that I use less often but are still useful include str_replace, which accepts a string, a sub string and a replacement sub string and it searches the string, for any occurrences of the sub string, replacing them with the specified replacement. Although this does seem to be very useful I usually use a regex/pattern approach using the preg_ functions.... Regex (or Regular Expressions) are a mini-language in themselves, specicially designed for pattern matching. They are extremely useful for searching log files for specific patterns ( say, a given connection that occurs at 8 am every day for 10 weeks might mean something). In addition we will look at them when we look at validating input - making sure the user isn't hacking our system
str_pos() and substr_count() return the first occurrence of given sub string, and the location of the sub string respectively - often are very useful for seeing if a certain string is in there ( eg, seeing if a user name contains "admin" at all - in order to ban it).
That's most of the extremely useful ones. In about 4-5 weeks we can start to use these functions in practice on our first mini-project
Dates
______________________________________
Ok, sooner or later you will have to work with dates. More specifically youll have to work with Unix Timestampes. These are essentially really ( fairly) large numbers, that each computer counts - its the number of seconds since Jan 1970 00:00:00.
CODE
$now = time(); // Whatever the current timestamp is.
This might equal something like 1234183142 (which was the timestamp when I ran the code on my server).
Once you have a timestamp, you'll want to be able to format it for your users - after all I know personally that I cannot tell the time in seconds from 30 years ago
Here we go:
CODE
date("l n/F/Y G:i:s", $timestamp); // "Tuesday 09/02/2009 23:45:56"
If you do not tell it what $timestamp you want, it assumes the time(), or the current time. Now there is a large table which explains what each character means however in short each letter stands for a part of the time, and the other "/" " " ":" characters are there for formatting. Think of it as though for each letter in that string, it is str_replace()ed with the correct value
Now, what if we don't know the timestamp, but we know the date values. Well we can use mktime(), who's arguments are the following:
CODE
mktime(hour,min,sec,month,day,year); // All of which are (int) values
.This will store the timestamp, same format as time().
Ok - and say you want to be programmer friendly, or your just lazy
strtotime(). You place in a string describing the time you want, and you get the timestamp out, heres an example:
CODE
$tomorrow = strtotime("tomorrow");
All of the following strings will work:
"Yesterday 3pm"
"now + 6 hours"
"next year"
"5 minutes ago GMT"
All of the following strings will work:
"Yesterday 3pm"
"now + 6 hours"
"next year"
"5 minutes ago GMT"
Now, I've added an interesting thing in the last one - a Timezome definition. Its not always 4pm around the world is it! So PHP goes on wherever the server's time/timezone is set to. Say for example you are running a website ( such as this one) who's members come from all over the world. It can get very confusing when the most recent post (5 minutes ago) was posted at 3 am, when its 6 pm for the user!. Well this happens when the server works at 3am, but the user is in a different timezone. Now I personally haven't perfected the method of storing timestamps. Usually I prefer to convert all timestamps into GMT - so that I can then convert them to any time I want. It can definitely get confusing and you will have to read through some of PHP's documentation to make sure that your own method or storing is correct etc. Either way - be aware that even if your local time may be 6 pm, the server might be on the other side of the world ( as was the case for my shared server before I purchased one hosted locally).
Just a small addition, you can easily find the difference between two times. Say for example you have two dates, and you need to find how long between them. simply subtract one from the other - and you have it
Woah!!! That was a lot for one lesson. To be honest, a lot of this stuff here can easily be looked up on the PHP website and the sooner you learn to do so the less youlul have to remember. Eventually as you begin to program in PHP more often - you'll find that you remember your own personal set of favourite functions, because there is not always only one way to achieve something - especially with strings.
Depending on the feedback I get this week, I may place Array's and functions into the one lesson - but if no one tells me how your going, then I won't because I don't want to speed ahead leaving people behind. Just for reference until I do teach functions - while looking up how to format strings etc, you are all using functions.
Functions (A 30 second overview).
A function does something. It might add one number to another, or it might accept a form and process it into a database, emailing the web master of a new entry. Either way its still doing "something". to call a function it is:
function_name ($argument1, $argument2.......); where the function name is (obviously) the name of the function such as "explode" or "substr". the $arguments, are values that you pass into the function. Generally, a function only knows about data you send into it using arguments. Some functions have optional arguments, such as date() where if the second argument isn't actually used, it makes the assumption of a certain value. Hopefully that will clear up a few things when your looking around PHP's function reference ( Text section, Strings subsection) - or http://au.php.net/ma...ref.strings.php to be specific.
Do look around the just named website, read through this again - and let me know if you have any problems. If I don't get any feedback I'll assume that everyone's fine and I'll post homework.
Thanks ( and goodnight!!!!),
Jack

Sign In
Register
Help


MultiQuote
