Archive for the ‘simple PHP code’ Category

Add this PHP code in functions.php file.


add_filter( ‘the_content’, ‘prefix_insert_post_ads’ );

function prefix_insert_post_ads( $content ) {

$ad_code = ‘<div> You can add ads code here </div>';

if ( is_single() && ! is_admin() ) {
return prefix_insert_after_paragraph( $ad_code, 1, $content );

return $content;

// Parent Function that makes the magic happen

function prefix_insert_after_paragraph( $insertion, $paragraph_id, $content ) {
$closing_p = ‘</p>';
$paragraphs = explode( $closing_p, $content );
foreach ($paragraphs as $index => $paragraph) {

if ( trim( $paragraph ) ) {
$paragraphs[$index] .= $closing_p;

if ( $paragraph_id == $index + 1 ) {
$paragraphs[$index] .= $insertion;

return implode( ”, $paragraphs );

simple PHP code | No Comments | October 22nd, 2008

n this tutorial I’ll discuss dates and time in PHP, which is useful for a
myriad of tasks. To kick things off, take a look at PHP’s time()
function, which displays the current time measured in the number of seconds
since the Unix Epoch (January 1 1970 00:00:00 GMT):

print time();

This is also called a UNIX timestamp, and as mentioned, displays the current
time in seconds passed since the Unix Epoch. A sample output may look like:


Using date() to display the date and time

Now, we want to display not just the current time and date, but in a user
friendly format. To do that we should enlist PHP’s date() function.
This date function is used to convert from a UNIX timestamp to a human readable
date. The date() function looks like:

string date ( string format [, int timestamp])

You can see that the timestamp is surrounded by ‘[‘ and ‘]’, which means it’s
optional. If we put it then the function will use it and if we don’t put it then
the function will use the default timestamp. The default timestamp which is used
when we don’t put any timestamp is the current time.

Let’s start our work with the date function. We want to show the user what
date and time is now.

print date(“l, F jS Y – H:i:s”);
//Example output: Tuesday, November 18th 2003 – 03:20:14

As you can see on the example above, I use l, F jS Y – H:i:s as the variable
passed to the function. Here’s a description of each of the formatting
characters used above:


month, textual, long; e.g. “January”


hour, 24-hour format; i.e. “00” to “23”


minutes; i.e. “00” to “59”


day of the month without leading zeros; i.e. “1” to

l (lowercase ‘L’)

day of the week, textual, long; e.g. “Friday”


seconds; i.e. “00” to “59”


English ordinal suffix for the day of the month, 2
characters; i.e. “st”, “nd”, “rd” or “th”


year, 4 digits; e.g. “1999”

But wait, PHP actually supports many other characters you can pass into the
date function to format the output. Here’s the complete list:



Example returned values


Lowercase Ante meridiem and Post

am or pm


Uppercase Ante meridiem and Post

AM or PM


Swatch Internet time

000 through 999


Day of the month, 2 digits with leading

01 to 31


A textual representation of a day,
three letters

Mon through Sun


A full textual representation of a
month, such as January or March

January through December


12-hour format of an hour without
leading zeros

1 through 12


24-hour format of an hour without
leading zeros

0 through 23


12-hour format of an hour with leading

01 through 12


24-hour format of an hour with leading

00 through 23


Minutes with leading zeros

00 to 59

I (capital i)

Whether or not the date is in daylights
savings time

1 if Daylight Savings Time, 0


Day of the month without leading zeros

1 to 31

l (lowercase ‘L’)

A full textual representation of the
day of the week

Sunday through Saturday


Whether it’s a leap year

1 if it is a leap year, 0 otherwise.


Numeric representation of a month, with
leading zeros

01 through 12


A short textual representation of a
month, three letters

Jan through Dec


Numeric representation of a month,
without leading zeros

1 through 12


Difference to Greenwich time (GMT) in

Example: +0200


RFC 822 formatted date

Example: Thu, 21 Dec 2000 16:01:07


Seconds, with leading zeros

00 through 59


English ordinal suffix for the day of
the month, 2 characters

st, nd, rd or th. Works well with j


Number of days in the given month

28 through 31


Timezone setting of this machine

Examples: EST, MDT …


Seconds since the Unix Epoch (January 1
1970 00:00:00 GMT)

See also



Numeric representation of the day of
the week

0 (for Sunday) through 6 (for Saturday)


ISO-8601 week number of year, weeks
starting on Monday (added in PHP 4.1.0)

Example: 42 (the 42nd week in the year)


A full numeric representation of a
year, 4 digits

Examples: 1999 or 2003


A two digit representation of a year

Examples: 99 or 03


The day of the year

0 through 366


Timezone offset in seconds. The offset
for timezones west of UTC is always negative, and for those east of UTC
is always positive.

-43200 through 43200


Using mktime() to manipulate past and future times

Another useful function in PHP is mktime(), which can help you
easily display and format a past or future time (ie: what day of the week is
your birthday on)? This function creates a timestamp from a given set of
variables that you pass to the function.

mktime(hour, minute, second, month, date, year);

Now, I want to know on what day of the week my birthday was on. My birth date
is July 21st 1974. I’ll use the mktime function like so:

$mybirthdate = mktime(0,0,0,7,21,1974);
print date(“l”, $mybirthdate);
//Output: Sunday

Wow, I finally found out that my birthday is on Sunday. :). Now the next case
I want to know is what day is 25 days from now. Let’s do it this way:

$next25day = mktime(0,0,0,date(“n”),date(“j”)+25,date(“Y”));
print date(“l”, $next25day);

Give attention to the variables that I passed to the mktime function. I’ve
passed date(“j”)+25. It means that I want to add 25 to the current date. You can
figure out what it will produce.

Using getdate() as an alternative to date()

This is another method to access the current date or the given timestamp. The
method, or you can call it function, is getdate(). This function
will produce an associative array containing the date information. The array
keys are:








day of the month


day of the week, numeric: from 0 as Sunday up to 6 as


month, numeric


year, numeric


day of the week, textual, full; i.e. “Friday”


month, textual, full; i.e. “January”

Example :

$today = getdate();
print $today[“month”] // it will print the month of current date
print $today[“weekday”] // it will print the day of current date

Displaying the date and time in your own local language

By this time I hope you can create your own date and time using the timestamp
of the current date or your own timestamp. I’m not using English as my primary
language, and neither are my website users. We are from Indonesia and I want to
display the date in Indonesian language. How can I do it? That’s a perfect
question and asked by most beginners.

Let’s create an associative array of date and month in our own language.

$days = Array (“Minggu”, “Senin”, “Selasa”, “Rabu”, “Kamis”, “Jum’at”, “Sabtu”);
$months = Array (1=>”Januari”, 2=>”Pebruari”, 3=>”Maret”, 4=>”April”,
5=>”Mei”, 6=>”Juni”, 7=>”Juli”, 8=>”Agustus”, 9=>”September”,
10=>”Oktober”, 11=>”Nopember”, 12=>”Desember”);

After we create our own language of date and months, now it’s time to display

print $days[date(“w”)]; // display name of day with our own language
print $months[date(“n”)];

Ok guys, that’s it for today. We’ll see you again next time.

simple PHP code | No Comments | October 22nd, 2008

Creating a simple feedback form using PHP is very easy, thanks to PHP’s prebuilt mail() function. In this tutorial I’ll show you a complete, working example.

Firstly, lets create the HTML portion of the form:

<form action="sendmail.php" method="POST">
<b>Your name :</b> <input type="text" name="name"><br>
<b>Your e-mail :</b> <input type="text" name="email"><br>
<b>Message</b><br><textarea name="message"></textarea>
<input type="submit" value="Send"><input type="reset" value="Clear">

This is a basic form with two input fields and a textarea. Since we are using the POST method, we’ll
be eliciting PHP’s $_POST variables within our PHP script to retrieve what’s been entered. Inside
the PHP script called “sendmail.php” (as that’s what we’re specifying above in our form),
enter the following:

/*Here we are going to declare the variables*/
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
//Save visitor name and entered message into one variable:
$formcontent="VISITOR NAME: $name\\n\\nFEEDBACK: $message";
$recipient = "";
$subject = "Contact Form";

Obviously, you’ll need to change the recipient to your own email address. If you want to send it to more than one email address, just put a comma in between them. You can also change the subject. By using the $_POST array of PHP, which is an associative array, we can access all the elements of the form.
Looking back at the first input field in the form, you will see name=”name”.
This is how we got the variables $_POST['name'] and $_POST['email'] and $_POST['message'] above- they came from each form element’s given name. In other words, you use each form element’s name attribute as the key to accessing its value within array $_POST.

Continuing with our “sendmail.php” script, we now need to construct a mail header which mail() requires before it can send the form to

$mailheader = "From: $email\\r\\n";
$mailheader .= "Reply-To: $email\\r\\n";
$mailheader .= "MIME-Version: 1.0\\r\\n";

These are simple mail headers. The first two tell the email program who it is from and who to reply to. The last one tells the
MIME-Version. All this information will be included in the email that’s sent to you. Finally, we’re now ready to invoke the mail() function to actually send the form:

mail($recipient, $subject, $formcontent, $mailheader) or die("Failure");
echo "Thank You!";

This executes the mail function with four parameters. It mails to the recipient with a subject, message, and headers. If it does not execute (die), it will print “Failure!”.

And now the complete “sendmail.php” script:

/*Here we are going to declare the variables*/
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
//Save visitor name and entered message into one variable:
$formcontent="VISITOR NAME: $name\\n\\nFEEDBACK: $message";
$recipient = "";
$subject = "Contact Form";
$mailheader = "From: $email\\r\\n";
$mailheader .= "Reply-To: $email\\r\\n";
$mailheader .= "MIME-Version: 1.0\\r\\n";
mail($recipient, $subject, $formcontent, $mailheader) or die("Failure!");
echo "Thank You!";

That is it!

simple PHP code | No Comments | October 20th, 2008

What is a Loop?

Looping is simply a way for you to reduce the amount of code and/or content you have to write out. The idea is that you have something you have to do, or some content you have to show, and instead of just “writing it all out,” you find a pattern to it – a common denominator – and let PHP execute the code or generate the content piece by piece using that pattern, based on a condition.

A condition is a way of letting PHP know how many times to run your loop, or when to stop running your loop. The ability to take a condition and execute a set of instructions over and over as long as that condition is true is one of the basic cornerstones of programming.

To demonstrate how loops work, we will use a “for” loop to solve the following example problem:

“Joe wants to be able to take a range of numbers and find out how many numbers are divisible by a certain number, within that range of numbers. “

The Code

Okay the first thing I am going to do is give you the complete script for the solution to this problem. That way, you have the goods right up front and can refer to it as a whole.

  1. <?php
  2. // variable to hold form
  3. $form = <<<SOMEFORM
  4. <form action = ‘{$_SERVER[‘PHP_SELF‘]}’ method = ‘post’>
  5. Range Start: <input type = ‘text’ name = ’start’ size = ‘3?><br />
  6. Range Finish: <input type = ‘text’ name = ‘finish’ size = ‘3?><br />
  7. Divided By: <input type = ‘text’ name = ‘num’ size = ‘3?><br />
  8. <input type = ’submit’ value = ‘Find Numbers’>
  9. </form>
  11. // if we have posted info…
  12. if ($_POST) {
  13. // assign post vars to reg vars for easier handling
  14. $start = (int) $_POST[‘start’];
  15. $finish = (int) $_POST[‘finish’];
  16. $num = (int) $_POST[‘num’];
  17. echo “The following numbers from $start to $finish are divisible by $num : <br />”;
  18. // loop from $start to $finish, 1 number at a time
  19. for ($x = $start; $x <= $finish; $x++) {
  20. // if the modulus of the current number and the divided by number
  21. // is zero, then it is evenly divisible by that number
  22. if (($x % $num) == 0) {
  23. // echo the number
  24. echo “$x ”;
  25. // end if
  26. // end for
  27. // end if
  28. // echo out the form
  29. echo $form;
  30. ?>

    What We Care About

    There may be a lot of things in that script you may be unfamiliar with. Basically there’s a form so we can get input from the user, and that’s about it. The only part of the script we are really going to focus on is this part:

    1. // loop from $start to $finish, 1 number at a time
    2. for ($x = $start; $x <= $finish; $x++) {
    3. // if the modulus of the current number and the divided by number
    4. // is zero, then it is evenly divisible by that number
    5. if (($x % $num) == 0) {
    6. // echo the number
    7. echo “$x ”;
    8. // end if
    9. // end for

      Let’s Get Loopy

      All loops are broken down into four basic pieces:

      – The initialization
      – The condition
      – The instruction
      – The iteration

      A basic “for” loop looks like this:

      for (initialization; condition; iteration) {

      We start out with telling PHP what kind of loop it is. Since it is a “for” loop, we start out by simply saying “for …” The initialization, condition, and iteration are put inside the ( )’s, separated by a semicolon. We use { } brackets to show where the start and end of our instruction is. Some people like to put the { on its own line like this:

      for (initialization; condition; iteration)

      It’s really just a matter of style; PHP doesn’t care either way.

    10. Going Around In Circles

      The Initialization
      This is where the loop starts. We tell the “for” loop where to start by assigning the starting number to a variable $x. In this example, our starting number is represented by $start – what the user puts in from the form.

      In a “for” loop, the initialization must always be a number. It doesn’t have to be a whole number, or even positive, but it has to be a number, and it has to be initialized by assignment to a variable, so that PHP can keep track of counting each iteration of the loop. In other words, it has to have this basic format:

      $x = $start;

      The Condition
      This is where we control how many times we want the loop to repeat, or iterate. A “for” loop counts from one number to some other number. This is where we tell PHP what that other number is. Without the condition, the loop will never stop repeating, and we would have what’s called an infinite loop.

      The condition must always check the initializing variable against a number value. It doesn’t have to be a whole number, it can be positive or negative, but it has to be a number value. You can use any of the normal condition operators for the condition. Some basic formats (that are relevant to our example) for the condition are:
      $x < $finish;
      $x <= $finish;
      $x != $finish;

      …And Again And Again

      The Iteration
      This is where PHP increments the initialization variable. In our example, we do $x++. This is just a shorthand way of doing $x = $x + 1, which is equally valid. it is also equally valid to increment it by something other than 1. It doesn’t even have to be a whole number. It can even subtract a number so your loop can “count down.”

      How you want your loop to count (the increments per loop, counting up or down, etc..) is entirely up to you, and you will base that on what your goal for the instruction is. In this example, we could just as easily start with the ending number and count down to the starting number, subtracting 1 from $x during each iteration of the loop, like so:

      1. for ($x = $finish; $x >= $start; $x–) {
      2. if (($x % $num) == 0) {
      3. echo “$x ”;
      4. // end if
      5. // end for

      On that note, be careful to “phrase” your loop correctly, or you will not get your desired results, or worse, end up with an infinite loop. Consider this loop:

      1. $start = 100;
      2. $finish = 200;
      3. for ($x = $start; $x >= $finish; $x++) {
      4. echo “$x ”;
      5. // end for

      We are telling the loop to start at 100, and while $x is greater than 200, run the instruction. Well the problem is, right out the gate, the condition is false, because 100 is not greater than 200. Our loop will never execute. Or how about this example:

      1. $start = 100;
      2. $finish = 200;
      3. for ($x = $finish; $x >= $start; $x++) {
      4. echo “$x ”;
      5. // end for

      Whoops, we accidentally put the start and finish variables backward. Since we start at 200, our loop will keep iterating as long as it is greater than 100. Each iteration, we add 1 to 200, so the condition will always evaluate as true. The loop will never stop, thus creating an infinite loop.

      Show Me The Money!

      The Instruction
      The Instruction is what you want PHP to do each iteration of your loop. It can be something as simple as echoing out the current iteration, doing some math based on each iteration, or pulling out a new row of information from a database. This is the “pattern,” or “common denominator” to your large chunk of code/content. It’s the individual brick that your loop stacks over and over to make your wall.

      The most challenging part of making a loop is the Instruction part. Finding the pattern isn’t always so easy as our simple condition to test if a number divides evenly by another number. You can use virtually anything inside your loop to build your pattern, from regular assignments/outputs to conditions; you can even put another loop inside your loop! And there’s really no limit to how far you can “nest” things inside one another, except for how far you can wrap your head around the logic. Finding a pattern to make a loop out of deserves it’s own tutorial altogether. It is what makes looping an artform.

      Raspberry Red, Lemony Lemon, Orangey Orange!

      Tucan Sam isn’t the only dude offering different kinds of loops. PHP offers four different ways to reiterate pieces of code:

      – The while loop
      – The do…while loop
      – The for loop
      – The foreach loop

      In principle, each kind of loop has the same basic components and does the same basic thing, but their nuances make it possible to write your code more efficiently, depending on your circumstance. The nuances in the loops are being able to put the loop’s components in different orders, or even combining components of the loop.

      Changing the order of the components is important to know, because this can and will change the outcome of your loop. For example, some loops or orders will execute the instruction first, then check the condition, so you will always get at least one iteration of the loop.

      The While Loop

      The basic While loop syntax looks like this:

      while (condition) {

      A working example might look like this:

      1. $x = 0;
      2. while ($x < 10) {
      3. echo “$x ”;
      4. $x++;
      5. }

      In essence, this while loop is exactly like a for loop. It has a set initializer, a set condition, and a set iteration. You are, of course, free to switch the order of the instruction and the iteration. In this example, it would actually be better to write this as a for loop, because that’s what the for loop was made for.

      The power of a while loop is being able to combine the initializer and even sometimes the iteration with the condition. One scenario in which this comes in handy is if you have a list of information in a database and you want to grab that information and make a loop to display that data, but you aren’t sure how many iterations there will be, because you aren’t sure how many rows will be returned from the database.


      1. $sql = “select name from table”;
      2. $result = mysql_query($sql);
      3. while ($name = mysql_fetch_assoc($result)) {
      4. echo “{$name[‘name’]} <br />”;
      5. }

      In this example, we run a query to select all the names in a table in your database. Inside the ( …), all 3 components (initialization, condition, iteration) are combined into a single expression.

      The initialization is easy enough to spot: $name = … is the initialization.

      mysql_fetch_assoc is a special function that grabs a name from the result source of the query and then internally increments the pointer of that result source to the next name in the results. This is the iteration, because when the loop finishes and goes back to the beginning, it will have a new name to fetch.

      The condition comes into play by the act of being able to initialize $name to the next name in the result source. If mysql_fetch_assoc gets to the end of the list of names, it will return false, so the next time the loop tries to assign a name to $name, it will fail, thus ending the loop.

      The Do…While Loop

      The do..while loop works pretty much exactly the same as the while loop, except that the instruction will always be executed first. The basic syntax looks like this:

      do {
      } while (condition);

      As with the while loop, putting the components in those positions makes it a glorified for loop, and you should use a for loop. Just like the while loop, the power is being able to combine the components and/or make a loop with an undetermined amount of iterations.

      If we were to use a do…while loop with the previous database example :

      1. $sql = “select name from table”;
      2. $result = mysql_query($sql);
      3. do {
      4. echo “{$name[‘name’]} <br />”;
      5. while ($name = mysql_fetch_assoc($result));

      In this example, we’re going to run into some problems. Because the instruction comes first, $name[‘name’] does not exist until after the first iteration of the loop. In my experience, there aren’t very many circumstances where a do…while loop is preferred over a while loop. It’s really only good for wanting to make a loop where you want the instruction to be executed at least one time, no matter what.

      The For Loop

      We used the for loop in our example on how loops work, so you should already have a decent understanding about this loop. The only thing to really understand about the for loop, is that it is the “strictest” loop out of the bunch. It needs a set starting point, and a set ending point. It’s useful if you know exactly how many iterations you are dealing with, simple as counting from 1 to 10.

      As shown previously:

      for (initialization; condition; iteration) {

      The condition will always be evaluated before the instruction is complete, and the instruction will be executed before the value is iterated.

      initialization -> condition -> instruction -> iteration -> condition -> instruction -> iteration …

      The Foreach Loop

      A foreach loop is specially designed for working with array elements. A basic structure of a foreach loop looks like this:

      foreach ($array as $value) {

      In this loop, the $value is the initialization component. The condition and iteration comes from the $array. The $array represents an array. The loop starts an internal pointer at the beginning of the array, and assigns the value of that element to $value, and then executes the instructions. When the instructions are done, the pointer is moved to the next element of $array (the iteration). If there is no element (the end of the array), the condition evaluates false, and the loop ends.

      Consider this example:

      1. $letters = array(‘a’,‘b’,‘c’);
      2. foreach($letters as $letter) {
      3. echo “$letter <br />”;
      4. }

      The foreach loop points to the first element of the $letters array, executes the instructions, moves to the next element, etc… and when it runs out of elements, the loop is over. The output would be:


      The foreach loop accommodates associative arrays, as well. An associative array is an array that assigns a “name” to the element, or key, of the array. Example:

      1. $account = array(‘name’ => ‘John’, ‘number’ => 123, ‘age’ =>30);
      2. foreach($account as $key => $val) {
      3. echo “$key : $val <br />”;
      4. }

      The output of this would be:

      name : John
      number : 123
      age : 30

      Continue and Break

      PHP offers two language constructs to break out of your loop: continue and break. “Continue” is used to skip the rest of the instructions in the current iteration of the loop. Let’s say you want to count from 1 to 100 but skip printing all the even numbers:

      1. for ($x = 0; $x <= 100; $x++) {
      2. if (($x % 2) == 0) {
      3. continue;
      4. }
      5. echo “$x <br />”;
      6. }

      Each iteration of the loop we have a condition to check if $x is evenly divisible by 2. If it is, we skip echoing out $x and move on to the next iteration. Now we could have just as easily done this:

      1. for ($x = 1; $x <= 100; $x = $x + 2) {
      2. echo “$x <br />”;
      3. }

      But that’s not the point! Besides, continue and break are useful for things much more complex than this. Break works the same way as continue, except that it breaks out of the whole loop, instead of the current iteration.

      Both break and continue can take an optional argument for you to specify what level loop to break or continue. This is useful for nested loops, where if you for example have a loop running inside another loop and if some condition is met, you want to exit out of the loop, even the main loop, you can do this:

      1. for ($x = 0; $x <= 10; $x++) {
      2. for ($y = $x; $y <= 10; $y++) {
      3. $z = $x * $y;
      4. echo “$x * $y = $z <br />”;
      5. if ($z == 50) {
      6. break(2);
      7. }
      8. }
      9. }

      In this nested loop, we are printing out everything from 1 * 1 to 10 * 10 but we have a condition inside the nested loop to break out of all of the loops if we find an answer that equals 50.

      That’s All Folks!

      Well, that’s about all there is to know about loops. The basic syntax of loops is pretty easy to figure out; it’s finding the patterns to loop that’s the tough part. I hope that this has helped some of you out there who are just getting started and want to know what’s the point of loops and why are there different kinds. Perhaps in a future tutorial I will attempt to tackle tips and tricks to finding patterns for loop instructions.

      Until then, happy coding!