Last Updated:

Programming on PHP

Programming on PHP

Not only is it very simple – it's also fascinating! You invariably come to this conclusion if you start to get acquainted with the basics of programming in the PHP hypertext preprocessor language.

Well, just the beginning is still there, and the already incomprehensible words have gone. I had to come up with this – a hypertext preprocessor! So to improve the perception of the material, let's agree in advance that we will use simplified and understandable terms for everyone, which would be clear to literally everyone.

And another indispensable convention is that we do everything the way we do. There are several ways to open the Control Panel in Windows, there are different ways to cook the same dish, and there are different ways and methods of programming. The task can be handled both as described and in a completely different way. But in our case, the emphasis will be on simplicity and logic, and not on the speed and purity of the code. All this will come a little later, but for now our goal is to learn, learn, and learn again.

Continuing the topic raised in the article "PHP for everyone!", we will delve further into the wonderful world of programming.

Cycles in PHP


Loops in programming are repeated operations several times. The beginning (reference point) is indicated at the beginning of the cycle, and the duration of its execution is limited by a condition. An example of a loop is copying multiple files. The algorithm for performing this task can be described as follows: set the number of copied files to zero, copy the file, check whether the files ran out or not, if not - increase the number of copied files, return to the beginning of the cycle (copy the file again), if yes - finish the cycle. Now let's look at how loops are implemented in PHP syntax.

$i = 0; $n = 10;
while ($i <= $n):
echo $i."

The meaning of the script is very simple. Assign a value to the variable that corresponds to the beginning of the loop, and to the variable $n - the value of the end of the cycle. Next, open the loop with the operator , and inside its brackets describe the condition under which the loop will continue its work. In our case, execution will not be interrupted until . As soon as this condition is violated, control will be transferred to the next PHP operation. Inside the loop, there can be any PHP commands (separated from each other as usual - with a semicolon). You just need to make sure that the variable used in the loop is increased (and not necessarily by one), otherwise the loop will become infinite, and the PHP interpreter will execute it until the session (browser window) closes.$iWHILE (  )$i <= $n$i

The operator means the end of the loop. The script described here displays numbers from 0 to 10 on the browser screen. Moreover, the numbers will be displayed in a column, since after displaying the value of the variable on the screen, we display the HTML-tag of the line feed ( ). It is followed by a line feed for the code passed to the client (it can be viewed by selecting html view in the menu of your browser). This is not necessary, but in this way the readability of the code is achieved.ENDWHILE$i

For example, I give another option for performing the above task, but much more correctly in terms of code purity and speed of execution.

$i = 0; while ($i <= 10) { echo $i++."
"; }

Surprisingly, these two examples are absolutely identical in terms of the result. But the script itself fit into one line! The difference is in the style of the loop operator and in the fact that the loop variable is displayed on the screen at the same time as the increase. And that's the beauty of programming. Sometimes it is very difficult to do something simple, and something difficult is easy. You should never stop at what has already been achieved, but try to apply other algorithms and solutions.

Here's another solution. It is based on the application of the PHP design. This is also a loop, but it differs from simply in that the value of the Boolean expression is checked not before (as in the case of ), but after the end of the work of the operators included in the loop itself. Thus, it is guaranteed to be performed at least once, which in the case of c is not at all necessary. After all, if the condition is a lie, control will immediately be transferred further.DO…WHILEWHILEWHILEDO…WHILEWHILE

For loops, there is only one kind of syntax:DO..WHILE

$i = 0;
do {
echo $i."
while ($i <=10);

It would seem that there are enough options, but that's not all - there are several more options for the cycle. And, as a rule, they are used by programmers.

Loops are the most powerful loops in PHP. They work similarly to their counterparts in the C programming language.FORFOR

FOR (expr1; expr2; expr3)

The first expression is unconditionally evaluated (executed) at the beginning of the loop. At the beginning of each iteration (cycle pass), the . If it is (true), then the loop continues and the nested operator(s) is executed. If it is equal to (false), then the cycle ends.(expr1)expr2TRUEFALSE

At the end of each iteration, the .expr3

Each of these expressions can be empty. If empty, the loop continues indefinitely (PHP by default considers it equal to , as in the C language). This is not as useless as it might seem, since it is often necessary to finish the execution of the loop using an operator combined with a Boolean condition instead of using a Boolean expression in . If this operator () occurs inside the loop (any), the loop unconditionally stops iteration and control is passed to the command following the loop.expr2TRUEBREAKFORBREAK

If an operator is encountered, control is transferred to the beginning of the next next cycle.CONTINUE

For example, let's see how else you can implement the display of a list of numbers on the user's screen. Do not forget about the transition from HTML to PHP.

/* example 1 */
for ($i = 1;
$i <= 10;
{print $i; }
/* example 2 */
for ($i = 1;
{ if ($i > 10) { break; } print $i; }
/* example 3 */
$i = 1;
{ if ($i > 10)
{ break; }
print $i;
$i++; }
/* example 4 */
for ($i = 1;
$i <= 10;
print $i, $i++);

So don't say later that you didn't have a choice :-) Using the example of a trivial task, we looked at how PHP allows you to achieve one goal in different ways. As a rule, in practice, the most suitable design is used, but often there is no need for this, it is enough to use the simplest and most logical option.

Send mail

Very often you want to know what happens on the site during your absence. Of course, you can periodically check the forum, guest room, etc. for new posts, but there is a better way! Why not send yourself a message to your mailbox when an event occurs on the site. As an example, I can offer such options as registering in the mailing list, entering a message in the forum, guest, etc., an error in opening a file, organizing feedback, polling readers' opinions about the posted article, etc., etc. There are a lot of ways to apply this RNR feature, it remains to understand how it works. As always – easy!

The syntax is as follows:

Mail( $email, "Message entered", $str, "From: message ");

Of course, before that, the corresponding variables must be entered either manually or using a form (you need to monitor the correspondence of variable names in the form and in the script). When this command is executed, the PHP interpreter will send an email with the text from the $str variable to the address specified in the variable . Everything else is official information, which may in some cases be omitted as unnecessary. For example, consider the system of control over visitors to certain pages of the site.$email

Such an opportunity may be needed to analyze visits to certain articles, pages, etc. We will need information about the visitor, which in the PHP is automatically available through environment variables. We will send this information to our mailbox. Just do not overdo it - each visit to such a page will cause an email to be sent, and the mailbox may be full.

<?php if (isset ($HTTP_X_FORWARDED_FOR))
{ $host = gethostbyaddr($HTTP_X_FORWARDED_FOR);
else{ $host = gethostbyaddr($REMOTE_ADDR);
$date=date('d M Y, H:i:s');
$str=("Date - $dateHost - $hostIP address - $ip---------------------");
mail( $email, "statistics", $str, "From:info");

If you place this PHP code on one of your pages, information about the visitor (this is the login date, host and IP address) will be in your mailbox. You can also send yourself a message when an error occurs (for example, opening a file) on the site:

$filename = "data.txt";
$fp = @fopen($filename,"r");
if ( !$fp ) { @mail( $email, "Error!", "Error opening file $filename !"); }

As usual, you can put the @ sign, and if an error occurs when sending mail, a message about this will not be displayed on the screen. Or you can just check whether the letter is gone or not:

if ( @mail( $email, "Test", $str) )
{ ... what to do if the letter is gone ... }
else { ... what to do if a sending error occurred (box, site, etc. not available) }

Strictly speaking, it is possible to pick up mail from any account, but this requires the expansion of PHP by connecting additional modules, and is not available in the standard delivery. If you specify multiple addresses separated by spaces in a variable, the information will be sent to all specified addresses. This opens a simple way to organize your own, independent of anyone system of mailings. Times and dates Since the conversation touched on the date, let's try to figure out how all this can be used for your own purposes. In PHP, the most commonly used function is in the format$emailDATE


There can be several parameters, and they are separated by a comma. Here is a list of valid parameters.

  • a - "am" or "pm"
  • A - "AM" or "PM"
  • d - day of the month, digital, 2 digits (in the first place zero)
  • D - day of the week, text, 3 letters; i.e. "Fri"
  • F - month, text, long; i.e. "January"
  • h - hour, digital, 12-hour format
  • H - hour, digital, 24-hour format
  • i - minutes, digital
  • j - day of the month, digital, without leading zeros
  • l (lowercase 'L') - day of the week, textual, long; i.e. "Friday"
  • m - month, digital
  • M - month, text, 3 letters; i.e. "Jan"
  • s - seconds, digital
  • S - English ordinal suffix, text, 2 characters; i.e. "th", "nd"
  • U - seconds from the turn of the century
  • Y - year, digital, 4 digits
  • w - day of the week, digital, 0 means Sunday
  • y - year, digital, 2 digits
  • z - day of the year, digital; i.e. "299"

Note the differences in the case. Each character in different cases has different functions. Now you can easily get information about the current time, and use it on your website. One of the most common options is to display the current time and date.

Of course, all this is done without problems on , but anyone who has seen these scripts will understand the difference (at least in size and speed of execution, not to mention the traffic from server to browser). Well, in my opinion, it is quite useless to display time, since every user in the Windows tray has it, but it is useful to display the date, month and day of the week (and even in Russian language).JavaScript

Let's start by greeting the visitor. It would not be a bad idea to display the appropriate phrase depending on the time of the visit. Said and done:

if ($h>=5 && $h<=11) echo "Good morning!";
if ($h>=12 && $h<=18) echo "Hello!";
if ($h>=19 && $h<=24) echo "Good evening!";
if ($h>=1 && $h<=4) echo "Good night!";

The figures of the desired time can be put any, depending on the personal concept of day and night :-) The next step is to display the date, day of the week, and month name. But before we start implementing the algorithm, we need to get acquainted with another important point in programming languages.

Arrays in PHP


If you have a clear idea of what an array is, I suggest you go straight to reading the next paragraph. If not, then that's what you're about to find out.

An array is a series of variables that are ordered by name and have a different index. For example, imagine that you have twenty names, and all of them need to be entered into the program. For convenience, you can call variables the same name and put a number at the end of each variable name according to the name number. You will get the simplest one-dimensional array.

Only any programming language (and PHP too!) provides a set of tools for more detailed and convenient work with such a set – an array. And the number (the so-called index) should be enclosed in square brackets. Suppose there are a number of string variables – computer, Internet, modem, monitor. Let's choose a name for the array , although any one is available, just like a regular variable. The index in arrays does not start with one, but with zero, and thus to enter our words into the array, we need to do this:$m

$m[0] = "computer";
$m[1] = “Internet";
$m[2] = “modem”;
$m[3] = “monitor”;

Now we have an array named $m and the maximum index (this is the number of elements in the array) is 4. It is 4, although the last filled element is 3. If we try to read an element with a 4th index, the result will be equal to an empty string, since there is simply nothing there. It is necessary to refer to the elements of the array by the name of the array and its index, which is the main convenience. For example, we can display all the elements of an array:

$i = 0;
while ($i < count($m))
{ echo $m[$i]."

The function gives us a number corresponding to the maximum index of the array. Thus, we always have the opportunity to know how many elements are present in a given array.count($m)

What else can you learn about arrays in PHP? There's something you can do... For example:

The function returns the current element of the array. Each array variable has an internal pointer (this is not an index, but a special parameter that usually either coincides with the index or exceeds it by one, but not necessarily) that points to one of its elements. In addition, all elements in the array are linked by a bidirectional list of pointers for additional purposes. An internal pointer points to the first element that was included in an array until you performed one of the functions that modify that pointer in that array. The function simply returns the array element that the internal pointer is currently pointing to. It does not move the pointer in any way. If an internal pointer points to the end of the list of items, returns (false).currentcurrent()current()false

Note: if the array contains empty elements (0 or "", an empty string), the function will return "false" for each of them. This indicates that the current element is a null value or you have reached the end of the array.

End - Set an internal array pointer on the last element.

Next -- moves the internal array pointer. Returns the next array element, from the current position of the internal array pointer, or "false"() if there are no more elements. If the array contains empty elements, then this function will return a "false" () for those elements as well. behaves similarly, with only one difference. It moves the internal array pointer forward one element before returning the element. This means that it returns the value of the next element and moves the internal array pointer over it.falsefalsenext()current()

If the end of the array is found when accessing the next element, it returns a "false" ().next()false

Prev - Moves the internal array pointer. Returns the previous element of the array, or "false" (), if there are no more elements before the current one. If the array contains empty elements, the function will return "false" on those elements as well. behaves similarly to , except that it moves the internal array pointer one position back instead of forward.falseprev()next()

Reset () - sets an internal array pointer on the first element.

Rsort () - sorts the array in reverse order (descending). Alphabetically as well. Unfortunately, the Russian alphabet has nothing to do with it.

Sort () - sorts the array. Exactly the same as the previous one, only in ascending order. Of course, this is not all the functions that are in PHP with respect to arrays. But the rest is often very specific and is sometimes solved by simpler methods.

Date in English


The script, which we will now consider, allows you to display the date on the visitor's screen in the format of the Russian language. I immediately warn you that the implementation of the algorithm of this problem is not the best. But it is workable, clear in all respects and simple. And most importantly - only what has already been described is used.

First, I will give the text of the script itself, and then I will describe it in detail.

//-- define an array for months --

//-- define an array for days of the week --

// ---- read the month
if ($m=="01") $m=1;
if ($m=="02") $m=2;
if ($m=="03") $m=3;
if ($m=="04") $m=4;
if ($m=="05") $m=5;
if ($m=="06") $m=6;
if ($m=="07") $m=7;
if ($m=="08") $m=8;
if ($m=="09") $m=9;

// ---- read the day of the week

// ---- read the number

// - extract the day of the week from
$den_nedeli = $e[$we];

// - extract the value of the month
$mesyac = $q[$m];

echo "Today is ".$chislo." ".$mesyac.", ".$den_nedeli;

Now let's look at how this script works. First, we need to define two arrays in which the Russian name of the month and the Russian name of the day of the week will be stored respectively. Since the month cannot be zero, we need to take care of entering an array element with a zero index. If an array index is not specified, it is taken to be equal to an internal pointer. If the array is empty and not yet defined, the internal pointer points to the first element (which has an index of zero).

Entering a new array element moves the internal pointer up by one, and thus ensures that the array value is subsequently entered into an array cell that has an index one unit larger than the previous one.

In principle, you can provide data entry into the array in different ways. But the one mentioned here is the simplest and most primitive. We simply assign the data we need to the elements of the array in turn, and thus populate it.

Exactly the same story is observed with the second array. Only here the index of the desired cells of the array is specified explicitly, and the internal pointer is set to the index that is specified. And after entering the value, it moves up one. The difference between the two methods is that if the array has already been defined earlier and the index is not specified when you type it, the array cell that the internal pointer points to will be populated. And it can be at the end! And if the index is specified explicitly, an internal pointer is set to its value, and the entry occurs in an explicitly specified cell.

Actually, more often arrays are much longer than those given in the example, and it is more convenient to use a special function that allows you to read the file specified in it and enter everything that is in this file into the array. Moreover, the separator is the line feed, which is very convenient.

The syntax of this function is −

$array name = file("filename");

Next, an array is formed with the specified name and values corresponding to the lines of the file.

When the arrays are defined, we need to read the month number. It is read with a leading zero if the month number is less than ten, and so we need to take care of cutting it off. Here you can also apply different algorithms and methods, but we will use a frontal solution - just compare the resulting solution with a number of previously known options and change the month number to the correct one without zero. The solution is rough, but understandable and already familiar to us.

Although it is not right to do so - there are more elegant methods. For example, check the received value for a leading zero, and if the check is true (the very first character in the string is zero), delete the first character.

Next, in the course of the script, we read the day of the week and the number. You do not need to do anything with the number, since the date will be clear to everyone, but the day of the week and the month should be processed. Extract the day of the week from the array we entered earlier. The day of the week number points to the cell of our array where the desired Russian name is stored, and thus we will get the correct value anyway. The number of the day of the week changes, the number (index) of the cell from which the value is read changes.

And here, unlike the array with the name of the month, zero corresponds to Sunday, which we took into account when entering the array of days of the week. Exactly the same operation is carried out for a month. Its number points to the array cell where the correct month name in Russian language is stored. And then - we display the result on the screen in an arbitrary form.



So, we got acquainted with the very important principles of organizing loops and arrays in any programming language. They also learned how to put into practice the ability to send mail and read the date. I have no doubt that you will be able to come up with many more examples for applying these things in practice. Feel free to experiment and try different options. That's how programming languages are learned – with examples. Use the Internet to search for new solutions and scripts, subscribe to the PHP newsletters for new information. If not everything is clear - feel free to ask questions, I will try to answer them to the best of my ability and knowledge. And never rest on your laurels, because there is always something that we do not yet know, but we want to...