While Loop

PHP while loops are similar to for loops, but with a different structure. Personally, I use for loops much more often than I use while loops. However, while loops have their own powerful uses that you will discover later in your programming life.

Example $i = 0;
while($i < 5)
{
echo $i; //write our variable’s value
echo “<br/>”; //line break
$i++; //increment operator
}
echo “End of while loop”;
Result 0
1
2
3
4
End of while loop

After seeing the while loop, you can probably see how it is like the for loop, but just with the first statement is outside of the loop, the conditional remains in the if like statement, and the second statement is embedded in an if like statement.

The first statement $i = 0; is simply setting our variable $i equal to zero. The conditional statement $i < 5 is holding down the fort as the only item in the if like statement. Finally, we get into the embedded code where our increment operator, $i++;, serves to advance the if like statement. From the results, we can see that the exact same thing happens here that happened in the previous for loop.

Example $i = 0;
do
{
echo $i; //write our variable’s value
echo “<br/>”; //line break
$i++; //increment operator
}
while($i < 5)
Result 0
1
2
3
4

Again, pretty similar to the example above, but there is actually one major difference. In the do while loop, the statements in the do while are always run once because the conditional is at the end. The conditional here tells the server to go back and run through the do part again. We set the variable $i equal to 0. Then, we run through the do part where we find our increment operator $i++;. The results are the same as the previous loops. Once the increment operator makes $i equal to five, we exit the loop and continue reading onto the next statement, echo ” End of while loop “;.

PHP while loop iteration

The image above shows how PHP loops or iterates through a while loop. If the condition is met, PHP executes the code in the parentheses after the while loop. After executing that code, PHP returns to the while loop condition and checks to see if the condition is true. If is it true, the code in the while loop is executed again. This process continues until the condition is no longer true.

Read and Write to File

Time to try our luck with reading and writing to files in PHP. PHP actually makes it really easy for us to do whatever we want with files; reading, writing, and deleting. We will first start off with reading a file.

Reading a file

Example
$myFile = "sampleFile.txt";
$fh = fopen($myFile, 'r');
$myFileContents = fread($fh, 21);
fclose($fh);
echo $myFileContents;
Result I am the sample file.

We start off by setting our file name with the $myFile set to “sampleFile.txt”. Then we open our established link with the $myFileLink variable by setting our file name and what we what to do with the file (r for read). We then move onto the most important line where we get the contents of the file with our variable $myFileContents. We use the fread function, and pass in our variable link as the first parameter followed by the number of characters we want to read (in this case 21 characters). PHP reads files similar to how you would. It starts with the beginning and proceeds through the file, so always remember you are starting from the beginning unless you tell it not to.

Now that is great and all to simply read the first 21 characters of a file, but what if we don’t know how many characters we want to read? We need to figure out a way to tell PHP the number of characters that are in the entire file. Good thing PHP already has a function that can help us.

Example
$myFile = "sampleFile.txt";
$myFileLink = fopen($myFile, 'r');
$myFileContents = fread($myFileLink, filesize($myFile));
fclose($myFileLink);
echo $myFileContents;
Result I am the sample file…Back off me.

The main difference between this example and the previous one is the filesize function. The filesize function simply gets the size of the file, which means we can use it to tell us the number of characters that are in the file. By inputting that function into the fread function we can tell PHP to read to the end of the file. You could also subtract from the filesize function if you wanted to leave off so many characters.

Writing to a file

No worries, writing to a file isn’t that much harder than reading from one. It is just a lot more dangerous, which is perfectly fine as long as you know what you are doing. So, let’s start writing to a file.

Example
$myFile2 = "testFolder/sampleFile2.txt";
$myFileLink2 = fopen($myFile2, 'w+') or die("Can't open file.");
$newContents = "You wrote on me...";
fwrite($myFileLink2, $newContents);
fclose($myFileLink2);

Remember that writing to a file will erase it immediately. So, if you are going to use the write function make sure you run it on some test content before you wipe out all of your important files. QUICK NOTE: make sure you have write permissions set on the folder. If the write permissions are not enable, the server will tell PHP that it cannot write to that file. We open the file link just like normal. Then, we set the variable $newContents to hold the content we want to write to the file. Finally, we use the fwrite function to write to our $newContents to our $myFileLink2. And of course, we close of file link like a good web developer that cares about his server.

Writing to the end of a file

We can write to the end of the file, known as appending. Using the previous example, you can simply change the w+ to an a. Append is exactly like write, but except it keeps the current contents and adds new contents to the end. Appending is much safer than using write, but sometimes you must write over a file. Please be careful.

Functions

PHP Functions are extremely useful, and they can save you from writing bunch of redundant code. These are arguably the most power component to any language. It can separate your code to create a sense of logical flow. You can also add parameters, or arguments to functions, where you can see that power at the bottom of this page. Functions have a limited scope, which I believe is an asset. This means that if you define a variable inside the function, you cannot reference that variable outside of the function.

Example function greetings()
{
echo “Greetings”;
}
greetings();
Result Greetings

Here, we have a function called greetings. After we define the function, we called the function with greetings();. Pretty simple, huh? Now, let’s make our functions even more useful by adding arguments.

Function Arguments

Example function sampleFunction($argument1)
{
echo $argument1;
}
sampleFunction(“Something”);
Result Something

Woot woot! We just used a parameter. A parameter is like a variable of the function that is defined when you call the function later. We can see how it is more useful in the next example.

Example function addingFunction($parameter1, $parameter2)
{
echo $parameter1 + $parameter2;
}
addingFunction(333,444);
Result 777

This is similar to the last example. At the end, we call our function addingFunction(). We pass in two parameters this time: 333 and 444. Where 333 is being passed into the addingFunction as $parameter1 and 444 is also passed in as $parameter2. Once they are both passed in, we echo the sum of the two parameters. In the result, you can see that echo sent back 777. The final statement that executed was more like echo 777;. Nice job!

Like I said, understanding functions is crucial to your success as a programmer.

Delete File

Deleting files in php isn’t extremely common, but it is sometimes necessary. Always remember that you should hesitate before deleting anything. PHP doesn’t have a special undo for what you delete. Now that I have warned you, let’s burn some files to the ground.

Unlink in PHP

Example
$myFile = "testFolder/sampleDeleteFile.txt";
unlink($myFile) or die("Couldn't delete file");

As you can see, it doesn’t take too much to delete a file. If you run into problems deleting files, try opening and closing the file before you actually delete it. Like so:

Example
$myFile = "testFile.txt";
$myFileLink = fopen($myFile, 'w') or die("can't open file");
fclose($myFileLink);
$myFile = "testFolder/sampleDeleteFile.txt";
unlink($myFile) or die("Couldn't delete file");

I should note that this is more of a hack rather than good practice. Try to always close your files shortly after you open them. All you are doing with the code above is opening the file again to ensure that you actually close it.

If Statements

In PHP, if statements are the foundation of programming logic. If statements contain statements that are only executed when the condition is satisfied. Let’s go through an example.

Simple If Statement

Example
$myVar = 1;
if($myVar==1)
{
    echo "It worked.";
}
Result It worked.

The if statement simply says, if the variable $myVar is equal to 1, then execute the statements inside of the { } brackets. If our variable had been equal to two, the statements inside of the if would not have been executed.

Comparison Operators

You already used one of these above. It was the ==, which asks if the thing before it is equal to the thing after it. If the answer is yes (true), we execute the statement. However, if the answer would have been no (false), we would not have executed the statement.

Example
$x = 7;
if($x===7)
{
    //this would be . $x
}
if($x==="7")
{
    //Since our variable $x is not a string this would be not executed because === is a strict operator, which makes sure that the variable is set to the correct value and type of the conditional variable.
}
if($x!=8)
{
    //this would be executed because != means that the variable is not equal to the conditional variable
}
if($x>8)
{
    //Since 7 is not greater 8, this would not be executed
}
if($x<8)
{
    //Since 8 greater 7, this would be executed
}
if($x>=7)
{
    //Since 7 is equal 7, this would be executed
}
if($x<=6)
{
    //Since 7 is not less than or equal to 6 this would not be . executed
}

You can see what each one of the comparison operators do above, but what if you wanted to use two of them simultaneously? You can by using the following logical operators.

Example
$x = 7;
if($x>=6 && $x<=8)
{
    //Since 7 is greater than 6 and 7 is less than 8, this statement would be executed
}
if($x==7 || $x>=8)
{
    //This if statement says if $x is equal to 7 or if x is greater than 8, then execute this statement. While x is not greater than 8, $x is equal to 7; therefore, it will execute the statement.
}
if(!($x==6))
{
    //Since $x is equal to 7, not 6, and we are checking to see if its false (with the ! before the condition), this statement would be executed
}

If, Else If, and Else

If statements can be just as simple as the examples above, but they can also be more useful when you combine the if statements with else if and else.

Example
$x = 6;
if($x == 8)
{
    $x++;
    echo "if($x = 8) and now x = " . $x; //This would not be triggered because $x is not equal to 8
}
else if ($x == 7)
{
    $x = 4;
    echo "else if ($x = 7) and now x = " . $x; //This would not be triggered because $x is not equal to 7
}
else
{
    $x = 20;
    echo "else and now x = " . $x; //This would be triggered because the other conditionals were not met
}
Result else and now x = 20

You might be asking yourself, “What is the point in an else if statement?” Well consider the following examples

Example
$x = 8;
if($x == 8)
{
    $x++;
    echo "if($x = 8) and now x = " . $x; //This statement would be triggered because $x is equal to 8
}
if ($x == 7)
{
    $x = 4;
    echo "else if ($x = 7) and now x = " . $x; //This statement would not be triggered because $x is not equal to 7
}
else
{
    $x = 20;
    echo " else and now x = " . $x;//This statement would be triggered because the other conditionals were not met
}
Result if(9 = 8) and now x = 9 else and now x = 20

Why did the if($x == 8) and the else both execute their statements? It is best to think of ifs as completely separate conditionals, but else if and else build off of whichever if they follow. So, if you had an if statement that was below another if statement, the first if statement would be separate from the second if statement just like the example above. However, the second if statement in the example above, has an else built onto it. Since the first if statement’s condition is satisfied, it executes its statements. The second if statement’s condition is not satisfied, but the attached else statement’s condition is satisfied. Therefore, $x is incremented in the first conditional, and “if($x = 8) and now $x = ” . $x is displayed on the screen. Also, we have the second if’s else that sets $x equal to 20, and “else and now $x = ” . $x is displayed on the screen.