PHP Files

PHP File handling

PHP includes a lot of built-in functions for handling files and directories. You can read, write, delete, and get lots of information on files thru the use of these functions. Note that before you start working with files, you have to make sure that you have the right permissions that will allow you to manipulate them. So while you’re trying to figure out why you can’t delete a file, it may be because the server doesn’t allow you to do that.

The creation and removal of files are completed with two functions: “touch()” and “unlink()”. “touch()” searches if a file exists, and if it doesn’t, it creates one, according to the specified filename; “unlink()” is used to remove the file passed on as an argument:

touch(“newinfo.txt”); //create a new file, if it doesn’t already exist unlink(“oldinfo.txt”); //delete a file 

Now that you know how to create a file, you should learn how to access it. This is done using the “fopen()” function, with requires a string containing the file path and a string containing the mode in which the file is about to be opened, which tells “fopen()” to open a file for reading, writing, or both. The complete list of the available modes can be found in the PHP documentation. “fopen()” return an integer, also known as a file pointer, which should be assigned to a variable. This will be used later on to work with the opened file. If a file cannot be open for whatever reason, “fopen()” returns FALSE. After you’re done with the file, you should remember to close it with “fclose()”, passing as an argument the file pointer.

$oldfp = fopen(“oldinfo.txt”, “r”); //opens a file for reading if(!$fp = fopen(“newinfo.txt”, “w”)) //tries to open a file for writing die(“Error opening file!”); //terminates execution if it cannot open the file fclose($oldfp); 

Reading from files is done with “fgets()”, which reads data from a file until it reaches a new line “n”, an EOF (end-of-file), or a specified length, in this order. So if you specify 4096 bytes but “fgets()” first reaches a new line, it stops further reading. You should know that after each reading or writing to a file, PHP automatically increments an index which holds the current position in the file. So if you have just opened a file, and then read 100 bytes, the next time you will want to read something else using the same file pointer, PHP will continue from where the 101st byte. The “fgetc()” is similar to “fgets()”, except that it returns only a single character from a file every time it is called. Because a character is always 1 byte in size, “fgetc()” doesn’t require a length argument.

$text = fgets($fp, 2000); //reads 2000 bytes at most $chr = fgetc($fp); //reads 1 byte only 

While you can read lines using “fgets()”, you need a way of telling when you have reached the end-of-file, so you won’t continue reading without any results. This is accomplished with the “feof()” functions, which returns “TRUE” or “FALSE”, weather the position of a file pointer is at the end of it. You now have enough information to read a file line by line:

$filename = "test.txt"; $fp = fopen($filename, "r") or die("Couldn’t open $filename"); while(!feof($fp)) {   $line = fgets($fp);   print "$line
"; } fclose($fp);

While “fgets()” works well around text files, you may sometimes want more functionality for your script. The “fread()” functions returns the specified amount of data from a file, and doesn’t take into consideration the end-of-line “n”, like “fgets()”. “fread()” also starts from the current file position, but if you’re not happy with it, you can always change it using the “fseek()” function.

fseek($fp, 100); //moves the file pointer to the 100th byte print(fread($fp, 15)); //outputs 15 bytes 

Any writing to a file is done with the use of “fwrite()” or “fputs()” functions, which both use a file pointer and a string to perform the writing:

fwrite($fp, “Hello from PHP!”);  fputs($fp, “Hello again from PHP!”); 

So far, these functions were great with a single user. However, on public web-sites, with many users accessing your scripts at the same time, your files could quickly become corrupt. PHP offers the “flock()” function, which will lock a file and won’t allow other processes to write or read the file while the current process is running. “flock()” requires a file pointer and an integer to do this:

flock($fp1, 1); //shared lock – allows read, doesn’t allow write  flock($fp2, 2); //exclusive lock – doesn’t allow neither read, nor write  flock($fp3, 3); //release lock – releases a shared or exclusive lock 

There are a lot of other functions that you can use with files like: testing functions – “file_exists()”, “is_file()”, “is_dir()”, “is_readable()”, “is_writeable()”, “is_executable()”; functions that return information on files: “filesize()”, “fileatime()”, “filemtime()”, “filectime()”. You can figure out what the function does by just reading its name; more information about them can be found in the PHP documentation.

PHP Functions

PHP Functions

A function is a block of code to perform a specific task. This block of code can be executed anywhere in the program by calling it’s name. A simple syntax of PHP function is:

//define a function function f_name() {    block of code to perform a task; } //call a function f_name();

Let’s make a simple code to make our first PHP function.

<html> <body> <?php function first_func() {   echo "This is my first PHP function."; } first_func(); ?> </body> </html>

We have made a function named, first_func. First, a function is created by using the keyword, “function” which is followed by the function name. The function name should be self explanatory so that it is easy to use in the program. A function name should start with an alphabet or an underscore and should not contain special characters except underscore. All the code of the function should be within a pair of curly braces. The function once created can be used anywhere in the program by just mentioning the name of the function. In the above example, we have called the function, “first_func” in the program after creating it. Let’s see the output:

This is my first PHP function.

When a function is created, the code within it is not executed. The function is merely created. The code within the function will be executed only when it is called.


Adding parameters in PHP function

In the example above, there are empty brackets after the name of the function. These brackets are empty because we have not used any parameters in it. Parameters can be used along with a function when a variable has different values in the program. Let’s see with the help of an example how parameters are used in a PHP function.

<?php function add($x,$y) {    $sum=$x+$y;      echo "The addition of $x and $y is $sum."; } echo "The addition of 4 and 2 using add function:<br/>"; add(4,2); echo "<br/>The addition of 8 and 5 using add function:<br/>"; add(8,5); ?>

In the above example, we have called the function, “add” twice. The result will be:

The addition of 4 and 2 using add function: The addition of 4 and 2 is 6. The addition of 8 and 5 using add function: The addition of 8 and 5 is 13.

Return values in a PHP function

Till now we have seen that we call a function and it executes the code within it. But suppose that the output of the function has to be used outside the function. In this case, the function returns a value. Let’s see this with an example.

<?php function add($x,$y) {    $sum=$x+$y;      return $sum; } echo "The addition of 4 and 2 using add function:<br/>"; add(4,2); echo "<br/>The addition of 8 and 5 using add function:<br/>"; add(8,5); ?>

The output will be:

The addition of 4 and 2 using add function: 6 The addition of 8 and 5 using add function: 13

PHP Loop

PHP Loop

PHP loops are used to execute some code again and again for some definite number of times. There are many types of looping statements in PHP. They are:

  • while loop
  • do…while loop
  • for loop
  • foreach loop

Let’s discuss each of these loops.


While loop

The while loop is used to execute the specified code as long as the condition is true. The syntax of the while loop is given below:

while (condition) code to be executed;

Let’s see a simple code to display numbers 1-10 by using while loop.

<?php $i=1; while (i<=10) {     echo $i."<br/>";       $i++; } ?>

This simple code displays the numbers 1-10 in separate lines.

1 2 3 4 5 6 7 8 9 10

Let’s see how the above code is executed.
First the value of “i” is initialised to 1. Then the condition is checked and since “i” is less than 10, the code within the while loop is executed and 1 will be displayed. Then the value of “i” will be incremented. and the condition will be again checked and the new value of “i”, i.e. 2 will be displayed. This will continue till the condition is true. Notice, we increment the value of “i” in the loop. You should have a statement in your while loop which will eventually cause the condition to be false. If you don’t do this, the loop will never stop and your program will appear “frozen”.


Do…while loop

A do…while statement is a modified version of while loop. The main difference between both these loops is that the while loop checks the condition before executing the code within it while do while loop executes the code once and then checks the condition. Do while loop is used when the code withing the loop has to be executed at least once irrespective of the condition. The syntax of do while loop is:

do {    code to be executed; } while (condition);

The following example will illustrate this:

<?php $i=1; do {     echo $i."<br/>";       $i++; } while ($i<=10); ?>

The output will be:

1 2 3 4 5 6 7 8 9 10

In the example above, the parser will initialize the value of “i” to 1 and then it will execute the code within the do while loop and then it will check the condition. So even if the condition is false, the code within the loop will be executed at least once.


For loop

The for loop is one of the most used loops because it is very logical and easy to use. The syntax of the for loop is:

for (initial; condition; increm) {      code to be executed; }

The syntax of for loop has three parts:

  • initial:Initialize the counter.
  • condition:The condition to be checked at the beginning of each loop. If the condition is true the code within the loop will be executed and if it is false, it will not be executed.
  • increm:Increment or decrement the counter.

Note that each part of the for loop is separated by semicolon. Below is a simple example:

<?php for ($i=1; $i<=10; $i++) echo $i."<br/>"; ?>

and the output will be:

1 2 3 4 5 6 7 8 9 10

Foreach loop

The foreach statement is used to loop through arrays. For the current value of the array, the code within the loop is executed. The syntax of the foreach loop is:

foreach (arrayname as value) {      code to be executed; }

Let’s see a simple example:

<?php $arr=array(1,2,3,4,5,6,7,8,9,10); foreach ($arr as $v) echo $v."<br/>"; ?>

The output will be:

1 2 3 4 5 6 7 8 9 10

PHP Arrays

PHP Arrays

An array is a data structure that stores one or more values in a single variable. Each element in the array has its own id. There are 3 types of arrays in PHP namely,:

  • Numeric Array: An array with a numeric ID key.
  • Associative Array: An array where each ID key is associated with a value.
  • Multidimensional Array: An array containing one or more arrays.

Let’s see each of these arrays.


Numeric array

Whenever some data is stored in an array, some ID is assigned to each value. In numeric array, the ID assigned to each value is numeric. Numeric arrays can be created in many ways. Let’s see those ways.

//  Method I   $name = array('Value1','Value2','Value3' ); //  Method II   $name[] = 'Value1';   $name[] = 'Value2';   $name[] = 'Value3'; //  Method III   $name[0] = 'Value1';   $name[1] = 'Value2';   $name[2] = 'Value3';

Let’s see each of these ways.

&lt;?php //  Method I   $name = array( 'Mike','Scott','Peter' );   echo $name[0].", ".$name[1].", ".$name[2]; ?&gt;

In the first method, the keys are assigned automatically but remember that the keys start from 0 and not from 1.

<?php //  Method II   $name[] = 'Mike';   $name[] = 'Scott';   $name[] = 'Peter';   echo $name[0].", ".$name[1].", ".$name[2]; ?>

In the second method too, the keys are assigned automatically and the keys start from 0.

<?php //  Method III   $name[0] = 'Mike';   $name[1] = 'Scott';   $name[2] = 'Peter';   echo $name[0].", ".$name[1].", ".$name[2]; ?>

In the last and the third method, we have assigned the keys ourselves. The output of all the three methods will be the same as given below:

Mike, Scott, Peter

Below is an example to make arrays more clear:

<?php 	echo "looping through array"; 	$x = array(0,1,4,9,16,25,36,49,64,81); 	for($j = 0;$j<10; $j++) 	{ 	    echo " $j  : $x[$j]"; 	} ?>

and the output will be:

looping through array 0 1 4 9 16 25 36 49 64 81

Associative Array

In associative array, the ID key is associated with a value. There are two ways of creating an associative array.

//  Method I   $name = array("key1"=>Value1, "key2"=>Value2, "key3"=>Value3); //  Method II   $name['key1'] = "Value1";   $name['key2'] = "Value2";   $name['key3'] = "Value3";

Let’s see both these methods.

<?php      $mdays = array("January" => 31, 		    "February" => 28, 		    "March" => 31, 		    "April" => 30, 		    "May" => 31, 		    "June" => 30, 		    "July" => 31, 		    "August" => 31, 		    "September" => 30, 		    "October" => 31, 		    "November" => 30, 		    "December" => 31 		   );      echo "February has ".$mdays['February']." days."; ?>

Now let’s see the second method.

<?php        $mdays['January'] = "31";        $mdays['February'] = "28";        $mdays['March'] = "31";        $mdays['April'] = "30";        $mdays['May'] = "31";        $mdays['June'] = "30";        $mdays['July'] = "31";        $mdays['August'] = "31";        $mdays['September'] = "30";        $mdays['October'] = "31";        $mdays['November'] = "30";        $mdays['December'] = "31";     echo "February has ".$mdays['February']." days."; ?>

The output of both the methods will be:

February has 28 days.

Multidimensional Array

In a multidimensional array each element in the main array can also be an array. A simple multidimensional array is normally visualised as a matrix. Let’s see the syntax to create a simple multidimensional array.

$name = array (     "array1" => array     (         "value1",         "value2",         "valuen"     ),     "array2" => array     (         "value1",         "valuem     ),     "arrayz" => array     (         "value1",         "valuey"     ) );

Below is an example to make multidimensional arrays more clear:

<?php $cds = array (     "Christina Aguilera" => array       (            "Impossible",            "Beautiful",            "Dirrty"       ),       "Kelly Rowland" => array       (            "Stole",            "Obsession"       ) ); ?>

To access the first cd of “Christina Aguilera”, the PHP script will be:

<?php echo "First cd of Christina Aguilera is ".$cds['Christina Aguilera'][0]; ?>

and the output will be:

First cd of Christina Aguilera is Impossible

PHP Switch

Switch statement

The “switch” statement is similar to a series of “If…else” statements. In many occasions, you may want to compare the same variable (or expression) with many different values, and execute a different piece of code depending on which value it equals to. This is exactly what the switch statement is for. The syntax of the “switch” statement will be:

<?php switch (expression) { case value1: { code executed if the expression has value1; break; } case value2: { code executed if the expression has value2; break; } default: code executed if none of the value is true; } ?>

Let’s discuss the above syntax step by step. Let’s consider the simple script given below using the if, elseif, else statements.

<?php if ($i == 0) echo "i equals 0"; elseif ($i == 1) echo "i equals 1"; elseif ($i == 2) echo "i equals 2"; ?>

Now we will use the switch statement for the above task. First we will use only the “switch” statement and see what happens.

<?php switch ($i) { case 0:    echo "i equals 0"; case 1:    echo "i equals 1"; case 2:    echo "i equals 2"; } ?>

Now, let’s see what the output will be. Suppose, the value of “i” is 1. The output will be:

i equals 1 i equals 2

which is certainly not the desired one. The switch statement is always used along with break. When the expression value matches any case value, it performs the code associated with it and when it encounters break statement, it comes out of the switch loop. If the break statement is missing, the pointer will perform all the statements subsequent to the matching case statement. In our example above, the value of “i” was 1. So the code underneath it was performed but since it did not encounter any break statement, the code beneath the subsequent case statement was also performed. So the correct script will be:

<?php switch($i) { case 0:    { echo "i equals 0";    break; } case 1:    { echo "i equals 1";    break; } case 2:    { echo "i equals 2";    break; } } ?>

The output of the above code will be what we desired, i.e.

i equals 1

If you look at the logic of the above program, there is no need to use break in the last case because the pointer will come out of the loop anyways. So, you can avoid using break statement in your last case. But if you have any confusion then use break in every case.

Now there’s only one thing remaining to be understood in the above syntax — “default”. The default case is similar to the else statement. The code in the default case is executed when the expression does not match any of the case values. The following example will make this clear.

<?php switch($i) { case 0:    { echo "i equals 0";    break; } case 1:    { echo "i equals 1";    break; } case 2:    { echo "i equals 2";    break; } default:    { echo "i does not equal any value";    break; } } ?>

If the value of i is 5, the output will be:

i does not equal any value

A point to remember:The default case should always appear as the last case in the switch statement.

PHP if else

If, If…else, elseif

Sometimes we want different actions to be performed for different actions. If, If…Else, and Elseif statements can be used for this purpose. Let’s have a look at each of these statements.


If statement

The most important is the “if” statement. It performs some actions if the specified condition is true. If the condition is not true, then the action will be ignored. The syntax of this statement is as follows:

if (condition) code to be executed if the condition is true;

Let’s see an example.

<html> <body> <?php $str="PHP"; if ($str=="PHP") echo "Condition is true."; ?> </body> </html>

Let’s see what the output of the above script will be.

Condition is true.

The value of str is “PHP”. Hence, we get the above output because the condition is true. If the condition had been false, there would have been no output. Consider the script given below:

<html> <body> <?php $str="Learn PHP"; if ($str=="PHP") echo "Condition is true."; ?> </body> </html>

We will not get any output here because our condition is false. If the action to be performed has more than one statement, all the statements should be enclosed within a pair of curly brackets. Look at the code given below:

<?php $str="PHP"; if ($str=="PHP") { echo "Condition is true."; echo "This will help to understand PHP better."; } ?>

The output will be:

Condition is true.This will help to understand PHP better.

If…else

The “if…else” statement provides an additional advantage. If provides the actions to be performed when the condition is true and when it is false. Let’s look at the syntax:

if (condition) code to be executed if the condition is true; else code to be executed if the condition is false;

Have a look at the following example:

<?php $city = "NJC"; if ($city == "NYC") { echo "Condition is true."; echo "I love NYC!"; } else { echo "Condition is false."; echo "I don't belong to NYC!"; } ?>

Since our condition is false, both the statements after else will be executed. Hence, the output will be:

Condition is false.I don't belong to NYC!

Elseif

The “elseif” statement helps us to check more than one conditions. First look at the syntax and then we will see how it works.

if (condition1) { code executed if condition1 is true; } elseif (condition2) { code executed if condition2 is true; } else { code executed if none of the conditions is true; }

Following example will make it more clear.

<html> <body> <?php $city = "LA"; if ($city == "NYC") { echo "I love NYC!"; } elseif ($city == "LA") { echo "I love LA!"; } else { echo "My city is not there!"; } ?> </body> </html>

The value of city is “LA”, hence, the output will be:

I love LA!

The “elseif” statement allows us to check multiple conditions. There can be multiple elseif statements.

PHP String Capitalization

String Capitalization

String capitalization is used to change the case of a string. There are three functions for this purpose namely, strtoupper, strtolower and ucwords. Let’s have a look at each of these examples separately.


strtoupper()

This function converts the entire specified string to upper case. Let’s see this with an example:

<?php $str="We capitalize this string!"; $str_upper=strtoupper($str); echo $str_upper; ?>

The output of the above PHP code will be:

WE CAPITALIZE THIS STRING!

By using this function, all the alphabets will be capitalized and the numbers and special characters will remain as they are.


strtolower()

This function converts the entire specified string to lower case. It’s functioning is similar to that of “strtoupper()” function.

Let’s see this example:

<?php $str="PHP is a good language!"; $str_lower=strtolower($str); echo $str_lower; ?>

The output of the above PHP script will be:

php is a good language!

ucwords()

This function capitalizes starting letter of each word in the string specified. This function comes in handy when writing a title or a heading. Let’s see this example that will demonstrate the function, ucwords():

<?php $str="This title will look good!"; $str_uc=ucwords($str); echo $str_uc; ?>

The output will be:

This Title Will Look Good!

This function ensures that the starting letters of each word in the string are capitalized. The rest of the string remains as it is. If there is a letter in upper case in the middle of the word, it will remain in upper case.

PHP substr_replace

substr_replace()-Replace a part of string

The substr_replace() function is complementary to the function that we discussed earlier – “str_replace()”. While in “str_replace()”, we specified the value that had to replaced, in “substr_replace()”, we specify the starting and the end points of the value to be replaced. It is a more mathematical function. “substr_replace” has four parameters. The syntax is as follows:

substr_replace(original, replace, start, length);

Let’s have a look at the above syntax:

  • original : The string in which replacement function has to be performed.
  • replace : The value with which the value has to be replaced.
  • start : The starting point from where the replacement has to start. It has to be a number. In case there is a negative number, it means number of characters from the end of the string.
  • length : It is an optional parameter. This value tells how many characters beginning from the “start” value have to be replaced. In case the value is negative, it means number of characters from the end of the string.

Now let’s see this with an example.

<?php $str="I am a sex!"; $str_girl=substr_replace($str, "girl", 7,3); $str_boy=substr_replace($str, "boy", -3, 2); echo "Girl:".$str_girl."<br/>; echo "Boy:".$str_boy; ?>

The output of the above code will be:

Girl:I am a girl! Boy:I am a boy!

The fourth parameter, length is optional. What will happen if we dont use this parameter? Let’s see.

<?php $str="I am a sex!"; $str_girl=substr_replace($str, "girl", 7); $str_boy=substr_replace($str, "boy", -3); echo "Girl:".$str_girl."<br/>; echo "Boy:".$str_boy; ?>

The output of the above script will be:

Girl:I am a girl Boy:I am a boy

This is the desired output. But do you see any difference in this output and the output above. The exclamation mark at the end of the statement is missing. The reason is that when you do not specify the length parameter, it replaces all the characters from the starting point to the end of the string, with the replace string.


Perform INSERT

The substr_replace function can also be used to insert a value in a string without replacing anything, simply by putting the parameter, length to 0. Let’s add something in our string above.

<?php $str="I am a sex!"; $str_girl=substr_replace($str, "girl", 7, 3); $str_boy=substr_replace($str, "boy", -3, 2); echo "Girl:".substr_replace($str_girl, "good ", 7, 0)."<br/>; echo "Boy:".substr_replace($str_boy, "good " , -3, 0); ?>

The output will be:

Girl:I am a good girl! Boy:I am a good boy!

This has performed our insert function.

PHP str_replace

str_replace()-Replace a string

The “str_replace()” function is used to replace some occurence in a string. It is very much similar to the “replace all” function in a word processor. It let’s us specify a word and what to replace it with, then replaces every occurrence of that word in the document. The syntax of the “str_replace()” function is:

str_replace(search, replace, string);

Let’s have a look at the above syntax. We will discuss each argument now.

  • search:This is the string that has to be replaced.
  • replace:This is the value with which the “search” string has to be replaced.
  • string:This is the string within which the whole replacement procedure has to be done.

We will see a simple example here in which we customise a string depending on whether a person is an adult or a child.

<?php $str="I am rep."; $str_ad=str_replace("rep", "adult", $str); $str_ch=str_replace("rep", "not an adult", $str); echo "adult:".$str_ad."<br/>; echo "not adult:".$str_ch; ?>

The output will be:

adult:I am adult. not adult:I am not adult.

In the above example, we had to replace a single value in the string. Suppose we want to replace multiple values in a single string. For this we will use arrays. We need two arrays for this purpose-one will store the “search” values and the other will store the “replace” values. Let’s see this with an example.

<?php $str="Welcome Birmingham parent! Your offspring is a pleasure to have! We believe pronoun is learning a lot. The faculty simple adores pronoun2 and you can often hear them say  "Attah sex!""; $search=array('offspring', 'pronoun', 'pronoun2', 'sex'); $malerep=array('son', 'he', 'him', 'boy'); $femalerep=array('daughter', 'she', 'her', 'girl'); $malestr=str_replace($search, $malerep, $str); $femalestr=str_replace($search, $femalerep, $str); echo "Son: ".$malestr."<br/>"; echo "Daughter: ".$femalestr; ?>

The output of the above script will be:

Son: Welcome Birmingham parent! Your son is a pleasure to have! We believe he is learning a lot. The faculty simple adores he2 and you can often hear them say "Attah boy!"  Daughter: Welcome Birmingham parent! Your daughter is a pleasure to have! We believe she is learning a lot. The faculty simple adores she2 and you can often hear them say "Attah girl! 

The above output is inconsistent with what we wanted. The “pronoun2” does not reflect the result that we wanted. Can you guess the reason?
The reason is very simple. The “str_replace” works step by step. First it will replace all the “offspring” value in the string, then it will replace all the “pronoun” values in the string and then it will proceed to “pronoun2” and then in the end to “sex” value. So when the function is replacing the “pronoun” value, it encounters “pronoun2” in the string and replaces it. Hence, the “pronoun” in “pronoun2” was replaced with “he” or “she”. So when the “str_replace” function started searching for “pronoun2”, it did not find any match in the string. Hence, the error.
A simple solution to this problem can be to place “pronoun2” before “pronoun” in the “search” array. So, the above code can be written correctly as:

<?php $str="Welcome Birmingham parent!<br/> Your offspring is a pleasure to have! We believe pronoun is learning a lot.<br/> The faculty simple adores pronoun2 and you can often hear them say  "Attah sex!""; $search=array('offspring', 'pronoun2', 'pronoun', 'sex'); $malerep=array('son', 'him', 'he', 'boy'); $femalerep=array('daughter', 'her', 'she', 'girl'); $malestr=str_replace($search, $malerep, $str); $femalestr=str_replace($search, $femalerep, $str); echo "Son: ".$malestr."<br/>"; echo "Daughter: ".$femalestr; ?>

And the output will be:

Son: Welcome Birmingham parent! Your son is a pleasure to have! We believe he is learning a lot. The faculty simple adores him and you can often hear them say "Attah boy!"  Daughter: Welcome Birmingham parent! Your daughter is a pleasure to have! We believe she is learning a lot. The faculty simple adores her and you can often hear them say "Attah girl!"

which is the result that we desired.

PHP strpos

strpos()-To find the position of a string or character within a string

The function, strpos() finds the position of a string within a string. It needs two arguments. First argument is the string in which you want to search and the second argument is the string that you want to search. When the function finds the string then it will return the position of the first match. In case it does not find a match, it will return false.

Let’s understand this with a simple example.

<?php echo strpos("Learn PHP", "PHP"); ?>

The result of the above script will be:

6

The strpos() function can also be used in the following manner:

<?php $str="Learn PHP"; echo strpos($str, "PHP"); ?>

The answer will be the same. Now, let’s see why the result was 6 and not 7. Remeber that the strpos() function always returns a value that is (position – 1). The reason is that the counter starts with 0 and not from 1. When you search for a string, then the position of the first character will be returned.


Finding position of a string using offset

The strpos() function has a third optional argument also. But what is the purpose? When we searched a string using strpos(), it returned the value of the first occurence of the string. But there can be more than one occurence of the string as well and we might be interested in it. For this, we can use the third optional argument in the strpos() function. Let’s see how.

<?php $str="Learn PHP. Master PHP."; $pos1=strpos($str, "PHP"); echo "The first occurence of PHP in the string is $pos1."; $pos2=strpos($str, "PHP", $pos1+1); echo "<br/>The second occurence of PHP in the string is $pos2."; ?>

The output of this script will be as follows:

The first occurence of PHP in the string is 6. The second occurence of PHP in the string is 18.