PHP Function – str_replace

The str_replace function is used to replace part of a string with another string. The syntax of this PHP function is detailed below:

<?
mixed str_replace( $search, $replace, $subject, $count );
?>

$search – This can either be a string value or an array of strings. This will be the string or strings you want to be replaced.

$replace – This can either be a string or an array of strings. These will be the value that is replaced when one of the $search items are found.

$subject – The string that will be searched and have replacements placed inside of it.

$count (optional) – The maximum number of times a replace should occur.

There are a number of reasons why you would want to use this function. One of the ways that I use str_replace is when I need to remove line breaks from the a large string that you are working with. You would do that by doing the following:

<?
$input = str_replace( "\n", '', $input );
?>

You may have noticed that I used $input as the return variable and the string that is having the replace performed on it. This is a quirk that I use in order to not have to create extra variables and you cannot pass the $input to the function as reference.

PHP Boolean Type

The boolean data type in PHP is very easy to use (and why should it be difficult, it is either True or it is False).

The basic way to set a boolean value is to use the true and false keyword. Unlike other programming languages, true and false are case insensitive so you can either use true, True, TrUe, or any other variation to get the same effect.

For example:

<?
$yes = true;
$yes2 = True;

$no = false;
$no2 = False;
?>

These are all valid ways to set a variable to true or false.

PHP has some interesting ways of determining if a variable is true or false. Since PHP is a dynamically typed language, nearly any type can be evaluated as true or false. The way you can keep this straight in your head is if the variable’s value is at its default state, it will likely be evaluated as false.

To be more official, here is how PHP evaluates true or false from various values:

  • the boolean FALSE itself
  • the integer 0 (zero)
  • the float 0.0 (zero)
  • the empty string, and the string “0”
  • an array with zero elements
  • an object with zero member variables (PHP 4 only)
  • the special type NULL (including unset variables)
  • SimpleXML objects created from empty tags

Text taken from PHP manual at: http://www.php.net/manual/en/language.types.boolean.php

Use cURL to Connect To Another System

cURL is a very useful tool used to pragmatically connect and interact with other systems to do various tasks like download a Web Page or RSS feed. It is also used to send information to another computer and get a response. A common example of using cURL is when you are purchasing something online. When you get your shipping quote or authorizing your credit card, you are very likely using something like cURL.

<?
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
$result = curl_exec ($ch);
?>

These 5 lines of code do a lot. In line 1 you begin creating your transaction by calling curl_init() and passing the URL you want to connect to (in this case we have a variable called $url).

Lines 2-4 set different options for the transaction. The CURLOPT_HEADER option is set to zero to signify we do not want the header information in the response. CURLOPT_RETURNTRANSFER tells cURL to assign the data we receive to a variable rather than simply output it to the screen. CURLOPT_POSTFIELDS sets what data we want to send in the header of our request. This is a very important option when interacting with other systems as this is generally where you will put your XML or other header data that is required by the system you are connecting with.

Line 5 actually executes the request. It will reach out to the $url, with $fields in the POST areas of variables and putting the data we received into the variable $result. With this variable you can do whatever you need in order to make your application work.

The Ultimate PHP CSV Parser

Lately I have been trying to find cool PHP utilities that I can use to handle my day to day tasks. Lately parsing CSV files in PHP has been something I have had to do over and over again. Such a basic task can be such a pain considering all of the different formats that they can be in (mostly the quotes around some of the values). I would do find and replace on the file to remove all the extra stuff and hope that I did not corrupt the data.

There had to be a better way to do this. I did some searching and I found Ming Hong Ng’s CSV Parsing class. It worked perfectly. I have parsed a ton of CSV files with no problems at all. You can download this class from: http://minghong.blogspot.com/2006/07/csv-parser-for-php.html

It is so simple to use too! Simply create an instance and call ParseFromFile or ParseFromString. The data is stored in the data instance variable. So simple!

This is something that should be apart of any PHP programmers toolkit.

Ternary Operator – Your Best Friend

If you have never used the Ternary Operator, or ? operator, your life is about to change. The ternary operator is used as a shorthand for if .. else structures that can really clean up your code. Some may want to classify this under a intermediate or advanced skill, but it is so useful that I think it should be included with the most basic tutorials.

Take this for example:

<?
if( $use_live_server ) {
     $url = "http://www.thelivesite.com"
} else {
     $url = "http://www.thedevsite.com";
}
?>

This block of code sets which URL we want to connect to based on if a variable called $use_live_server. While the block of code is perfectly valid, there is a much better way to do the exact same thing in a single line of code.

<?
$url = $use_live_server ? "http://www.thelivesite.com" : "http://www.thedevsite.com";
?>

That one line of code does the exact same thing and once you understand how this works. Here is how the ternary operator works:

<?
$variable = $expression_to_evaulate ? true : false
?>

You do not necessarily have to have a variable that is true or false. You can do any expression you need to.

Separating HTML From PHP Code

The first thing you will notice in all PHP programs is the use of special tags that tell the webserver to have PHP to process the code inside of those tags.

There are a few different versions of the tag that can be used.  The default version is:

<?php
// Code To Be Executed
?>

Any code between these two tags will be processed.  Anything outside of them will not be processed and outputted as it is typed.

There is also a short tag that can be used if you set the short_open_tag value in your php.ini file to 1.  This tag is:

<?
// Code To Be Executed
?>

PHP Hello World

Not be cliché, but I any book, tutorial or website discusses a programming language always begins with a program that simply displays the text “Hello World” on the screen and I intend to follow that tradition.

The process of writing text in PHP requires you to use either the “echo” of “print” function. There are some very minute differences between these two functions, but for these purposes, we will just say that they are interchangeable. If you really want to know the differences, there is an article that details this here.

Anyways, here is the hello world program for PHP.

<?
echo "Hello World";
?>

You could also use the print function and that would look like this:

<?
print "Hello World";
?>

You will notice that at the end of each line of code there is a semi-colon. Like many other languages, this is used at the end of most of the lines of code.

PHP Variable Syntax

PHP is a dynamically typed language. What this means is that you do not have to specify the variable type. You do not even need to declare you variable before using it. All variables have a $ in front of them and cannot be more than 64 characters long. String variables require that the value be surrounded by double or single quotes. Numerical values do not need to surrounded by quotes, but they can be if you so desire. They will still be recognized as numerical (PHP is nice that way).

For example, here are some basic variable declarations:

<?
$address = "123 Somewhere"; $zip = 49123
?>

Querying A mySQL Database Using PHP

Querying a mySQL database requires an established connection to a mySQL database.  You can read our article on connecting to a mySQL database here.

Querying the mySQL database is as simple as creating the SQL query and passing it through the mysql_query function.

<?
$sql = "SELECT * FROM products";
$results = mysql_query( $sql, $resource );
?>

With the $results variable you can use it to do a few different things. The first one we will discuss is to determine the total number of rows that was returned by the Select query. You can do that by doing the following:

<?
$num_rows = mysql_num_rows( $results );
?>

It should be noted that using mysql_num_rows is not the most efficent way to determine the number of rows being returned. If there are a lot of rows (I have seen it happen with as few as 1000 rows) that it is faster to query the database for the number of results like this:

<?
$sql = "SELECT COUNT(*) as num_rows FROM products";
$num_rows = mysql_fetch_array( mysql_query( $sql ) );
?>

This example also introduces the mysql_fetch_array function. This function is used to grab the next row of a mySQL query result. The row is returned as an array with the indexes named as the names of the columns in the database. Once there are no more results the function returns null.

The best way to iterate through a result set of a mySQL query is to use a while loop:

<?
$sql = "SELECT * FROM products";
$results = mysql_query($sql);
while( $row = mysql_fetch_array($results) ) {
    echo $row['products_id'] . ': '. $row['products_name'] . '
'; } ?>