String Explode and Implode

Onto my two favorite string functions in PHP, explode and implode.

PHP Explode

The explode function is awesome because it breaks a string into manageable parts, like words. You can easily create a PHP program using explode and other PHP functions to create a program that performs a word count. I crafted a program like this in college because I have a terrible tendency to use the same words, and apparently professors think that means you have a limited mind. I showed them. Enough bragging, more coding.

Example
$myString = "I am a long and redundant sentence that serves no purpose except to be an example.";
print_r(explode(" ",$myString));
Result Array ( [0] => I [1] => am [2] => a [3] => long [4] => and [5] => redundant [6] => sentence [7] => that [8] => serves [9] => no [10] => purpose [11] => except [12] => to [13] => be [14] => an [15] => example. )

We employ our print_r class to print out our array in a way that is readable. Inside that function, we have our explode function. First, we say that we want to separate everything by spaces, ” “, and we want to break up $myString. We could pass anything we want into the first parameter, and PHP will find any matches and explode the parts around it into an array. However, when you match something using explode, it does not include the matched string. In our example, we matched spaces, but in our array the spaces are completely eliminated. There is a third optional parameter to limit the number of words you want to break up, which you can add on the end. PHP Explode is finished. Let’s be more constructive in the next section.

PHP Implode

Enough of blowing things apart. Let’s start putting them back together with the PHP implode function. The implode function essentially does the opposite of the explode function. You can take an array and join it together and make it into one string instead of an array. Ok, we’re sorry. We’ll put it back together.

Example
$myString = "I am a long and redundant sentence that serves no purpose except to be an example.";
$newArray = explode(" ",$myString);
echo implode(" ",$newArray);
Result I am a long and redundant sentence that serves no purpose except to be an example.

Our code is almost identical to the example above, but we are not printing it out until we use our next function implode. In our implode function, we simply say we want to join all of the items in our array $newArray together, but please separate them with a space, ” “. Boom! We blew a string into pieces, and then put it again together like a boss.

For Loop

PHP for loops are a complicated concept. It is a combination of a statement, a condition, and another statement. Basically, a loop is a repeating if statement. Let’s just go ahead and jump into an example.

Example for($i = 0; $i < 5; $i++) //statement 1 var $i = 0; condition $i<5; statement2 $i++;
{
echo $i; //write current value of variable $i
echo ‘<br/>’;
}
echo ” End of for loop “;
Result 0
1
2
3
4
End of for loop

The for loop is somewhat like a modified if statement that restarts itself until the condition is satisfied. Inside of the for loop, we have the statement $i = 0; that declares a variable $i and sets it equal to 0. Next, we have the conditional $i < 5 that is the if part of the statement. We know that the conditional says if $i < 5, then run the statements in the { }. Finally, we have an increment operator statement, $i++, which is the most commonly used way to advance a for loop. Since the ++ is after the variable, we will increment i after all of the statements in the { } have been executed. This is exactly why when we echo $i for the first time it is 0 rather than 1. So, we run through the statements in the { } and we get the results 0,1,2,3,4. Right after the final execution of statements, $i is incremented to 5, which was then compared against the conditional $i < 5. It is obviously false at this stage; therefore, we move outside of the for loop and we execute the next line of code that happens to be our echo ” End of for loop “; statement.

PHP For Loop iteration

In the image above, we can see how PHP runs through a for loop. Every time all of the code has been executed in the parentheses, PHP goes back up and checks the condition in the for loop. If the condition is still true, PHP executes the code in the parentheses again until the condition is no longer true.

Files

There are many times where a developer needs to access different files on the server. You might want to read or write to some text or XML file for one reason or another. I highly recommend trying to use databases before using files to store data, but sometimes there are a few good reasons to use files. PHP file handling is very powerful stuff, so I have broken this up into a few sections. Let’s see the basics of opening and closing a file.

Example
$myFile = fopen("sampleFile.txt","r")  or exit(); //opens the file

Nothing to special here. We simply call fopen with our file location, which is sampleFile.txt, and then we specify the mode, which is r for read here. PHP just needs to know where the file is, the file’s name, and what we plan to do with it. Since I just have the file name, PHP assumes that the file is in the same directory as the file with this example code. The next section of this tutorial will cover how we tell PHP what we want to do with the file.

File Open Modes

PHP requires us to tell it what we would like to do with the file we are about to open before we open it. It needs to know these things for a few reasons. The main reason is PHP needs to know what permission it needs to do what you want with the file. If the file has read only access, PHP would like for you to only ask it to read the file because writing to the file will make PHP and the server grumpy. There are 6 important modes in the file opening process.

  • r – read only from the beginning of the file
  • r+ – read and/or write only from the beginning of the file
  • w – clears file’s contents and writes to the file from the beginning (Creates a new file if it doesn’t exist)
  • w+ – clears file’s contents and read/write to the file from the beginning (Creates a new file if it doesn’t exist)
  • a – appends to file’s existing content (Creates a new file if it doesn’t exist)
  • a+ – appends to or reads file’s existing content (Creates a new file if it doesn’t exist)

With every file that we open, we should always close it. So, let’s do just that.

Example
$myFile = fopen("sampleFile.txt","r")  or exit(); //opens the file
fclose($myFile); //closes the file

This example is just like the previous example, except for the bottom line. The fclose is our way to tell PHP we are done with the file and that it can be closed. It only has one parameter, which is the name of the file variable. Simple enough? I think PHP does a great job with memory management, but you should always close your files just to be extra sure you don’t create huge memory leaks. Let’s move onto doing stuff with the file.

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.