<?xml version="1.0" encoding="UTF-8"?>
<!-- generator="wordpress/2.0.4" -->
<rss version="2.0" 
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	>

<channel>
	<title>PHP Tutorials</title>
	<link>http://www.kekh.com</link>
	<description>PHP Tutorials</description>
	<pubDate>Fri, 25 May 2007 13:35:14 +0000</pubDate>
	<generator>http://wordpress.org/?v=2.0.4</generator>
	<language>en</language>
			<item>
		<title>Why PHP?</title>
		<link>http://www.kekh.com/chapter-1/why-php/</link>
		<comments>http://www.kekh.com/chapter-1/why-php/#comments</comments>
		<pubDate>Fri, 24 Nov 2006 08:01:33 +0000</pubDate>
		<dc:creator><ADMINNICENAME></dc:creator>
		
	<category>Chapter 1</category>
		<guid isPermaLink="false">http://www.kekh.com/uncategorized/why-php/</guid>
		<description><![CDATA[
 




 




PHP is an excellent choice for Web programming. It has many advantages over other languages, including other Web-oriented languages. To get a very general understanding of how the common Web programming languages compare, let&#8217;s compare them.
ASP is Microsoft&#8217;s Web programming environment. (It&#8217;s not a language itself because it allows the programmer to choose [...]]]></description>
			<content:encoded><![CDATA[<p></p><p>PHP is an excellent choice for Web programming. It has many advantages over other languages, including other Web-oriented languages. To get a very general understanding of how the common Web programming languages compare, let&#8217;s compare them.</p>
<p>ASP is Microsoft&#8217;s Web programming environment. (It&#8217;s not a language itself because it allows the programmer to choose from a few actual languages, such as VBScript or JScript.) ASP is simple, but too simple for programs that use complex logic or algorithms.</p>
<p>TIP</p>
<p>An algorithm is a formula-like method for accomplishing a particular task. Here&#8217;s a simple example: Some bank accounts use the last four digits of a person&#8217;s Social Security number as his PIN number. An algorithm could be formed to create this PIN number based on the already-known Social Security number.</p>
<p>Besides ASP&#8217;s over-simplicity, many companies find it hard to budget for the expense of Microsoft licenses. Without even considering hardware costs, a Microsoft server could cost thousands of dollars in licensing, whereas a comparable Unix-based operating system running PHP could be free.</p>
<p>TIP</p>
<p>Many people new to open source software find the idea of free software hard to believe. However, once you&#8217;ve spent some time looking into it, you realize how much open source software makes sense. In addition to open source software being free, it is generally updated and patched more frequently, and it&#8217;s usually easy to find help from other users and even from the developers of the software.</p>
<p>You may be interested in visiting http://www.OpenSource.org for more information.</p>
<p>Another language well known for its use on the Web is Sun Microsystems&#8217; Java. Java is praised for being platform-independent (a program written in Java can be run on virtually any computer without having to make any modifications to the program).</p>
<p>NOTE</p>
<p>The term platform means the same thing as operating system. Some examples include Windows, Solaris, Linux, FreeBSD, and NetWare.</p>
<p>Although Java does have its advantages, it has serious downsides in development time, development cost, and execution speed. Java development is time-consuming because projects in Java must follow strict rules (imposed by Java) that require extensive planning. In addition to high development time, the cost is also high because Java developers are expensive to hire. The cost is therefore potentially much higher than it would be if the project were done in another language. Even after the project is built, a program written in Java takes longer to run than one written in one of the other languages to which we&#8217;re comparing.</p>
<p>Overall, when compared to Java, PHP comes out with flying colors. It is not unheard of for a Java project to take two or three times the time to develop compared to a similar project in PHP. On top of that, the final program runs on a wide array of platforms (like Java), except the PHP program runs faster.</p>
<p>Another language commonly used for writing Web programs is Perl (practical extraction and report language). Perl, like PHP, is an open-source project developed to run on many platforms. In fact, Perl has been around longer than PHP. Before PHP, Perl was generally accepted as the best Web programming language. However, during the past few years, PHP has earned a reputation for being better than Perl for Web programming because PHP provides a vast number of features as part of PHP itself, whereas you would have to download separate modules to get the same functionality in Perl. This leads to problems when programs are transferred from one system to another because the modules have to be downloaded from Perl&#8217;s exhaustive (and confusing) module archive known as CPAN.</p>
<p>The last language to compare PHP to is C. C has been around for a long time; it has been used in a variety of computers, from mainframes to consumer PCs. The problems creating a Web program in C are obvious if you know C. To develop a Web program in C, you have to develop all of the basic functionality of Web programming (such as collecting the data from HTML forms) before you can even begin to think about the actual task at hand. Since PHP provides for all the common (and many uncommon) Web programming tasks, writing such a program in PHP allows the programmer to get straight to the point.</p>
<p>You could write volumes on PHP&#8217;s advantages over other programming languages when it comes to Web programming. There are many, many articles on the Internet comparing PHP to Java, Perl, ASP, and others. Once you&#8217;ve earned some experience programming in PHP, you might find yourself trying to convince your client or employer to allow you to use it instead of another language. If that problem arises, you should find plenty of helpful information by doing a Web search.</p>
<p>PHP has an unlimited number of uses. The original version was used solely to track who was viewing the creator&#8217;s résumé. Over time, however, that simple tracking program evolved into a language of its own.</p>
<p>TIP</p>
<p>If you&#8217;re interested in knowing how PHP came to be what it is today, I recommend visiting http://php.net/manual/en/intro-history.php, where you will find a brief history of the language.</p>
<p>PHP&#8217;s primary use certainly isn&#8217;t to track résumés anymore; it has grown to be able to do that and just about anything else. To giveyou a better idea of what PHP can do, here are some of its common uses:</p>
<p>Feedback forms</p>
<p>Shopping carts and other types of e-commerce systems</p>
<p>User registration, access control, and management for online subscription services</p>
<p>Guest books</p>
<p>Discussion and message boards
</p>
]]></content:encoded>
			<wfw:commentRSS>http://www.kekh.com/chapter-1/why-php/feed/</wfw:commentRSS>
		</item>
		<item>
		<title>If You&#8217;re New to Programming</title>
		<link>http://www.kekh.com/chapter-1/if-youre-new-to-programming/</link>
		<comments>http://www.kekh.com/chapter-1/if-youre-new-to-programming/#comments</comments>
		<pubDate>Sat, 26 Aug 2006 20:20:12 +0000</pubDate>
		<dc:creator><ADMINNICENAME></dc:creator>
		
	<category>Chapter 1</category>
		<guid isPermaLink="false">http://kekh.com/chapter-1/if-youre-new-to-programming/</guid>
		<description><![CDATA[If you&#8217;ve never written a computer program before, the whole idea may be quite intimidating. Most programmers will probably tell you (if they aren&#8217;t embarrassed to admit it) that they were intimidated when they began. However, the programming process isn&#8217;t all that difficult and, contrary to popular belief, you don&#8217;t have to have an extremely [...]]]></description>
			<content:encoded><![CDATA[<p>If you&#8217;ve never written a computer program before, the whole idea may be quite intimidating. Most programmers will probably tell you (if they aren&#8217;t embarrassed to admit it) that they were intimidated when they began. However, the programming process isn&#8217;t all that difficult and, contrary to popular belief, you don&#8217;t have to have an extremely high IQ to be good at it.</p>
<p>When you write a program, your main goal is to translate your idea into a language that the computer can understand. For example, if you were teaching a person how to cook hamburgers, you would first describe the process of forming the ground beef into patties. Then, you would tell the person how to put the burgers on the grill, how long to leave them there, and finally how to remove them.</p>
<p>Of course, just because you can describe the process of making hamburgers doesn&#8217;t mean PHP is going to be cooking anything for you anytime soon. The point is, if you can describe a process like I just described making hamburgers, you can write a program.</p>
<p>Writing a PHP program is simply the process of describing to PHP how to do something. By the time you&#8217;ve finished reading this book, you will understand all the concepts behind writing a PHP program. Those concepts are like the words and sentences used to describe hamburgers. The more you read this book, the more &#8220;words&#8221; you will understand, and the better you will be able to &#8220;describe&#8221; your task to PHP. Thus, you will learn to write PHP programs to suit whatever need or idea you have, and soon it won&#8217;t be any more intimidating than telling someone how to cook hamburgers.</p>
<p>Some programming problems might be very complex when examined as a whole. For example, creating a shopping cart is definitely not a simple task. However, a shopping cart can be broken into a few smaller tasks. Those tasks might include adding and removing items, which are both tasks that can break into even smaller tasks. You will find that any task, no matter how complex, can be broken into smaller ones until each task is simple enough that breaking it down further is unnecessary. This process is explained in more detail when you begin creating programs with more complexity (especially in Chapter 17, &#8220;Putting It All Together,&#8221; when we walk through the whole process of creating a complex program step-by-step).
</p>
]]></content:encoded>
			<wfw:commentRSS>http://www.kekh.com/chapter-1/if-youre-new-to-programming/feed/</wfw:commentRSS>
		</item>
		<item>
		<title>Writing a Basic PHP Program</title>
		<link>http://www.kekh.com/chapter-1/writing-a-basic-php-program/</link>
		<comments>http://www.kekh.com/chapter-1/writing-a-basic-php-program/#comments</comments>
		<pubDate>Thu, 24 Aug 2006 20:29:27 +0000</pubDate>
		<dc:creator><ADMINNICENAME></dc:creator>
		
	<category>Chapter 1</category>
		<guid isPermaLink="false">http://kekh.com/chapter-1/writing-a-basic-php-program/</guid>
		<description><![CDATA[Before we get into an actual program, let&#8217;s take a look at the steps we&#8217;ll take to create one. The steps aren&#8217;t complicated; in fact, they&#8217;re basically the same as the steps you use when creating an HTML page and publishing it to your server.
Unlike creating an HTML page, creating a PHP program requires that [...]]]></description>
			<content:encoded><![CDATA[<p>Before we get into an actual program, let&#8217;s take a look at the steps we&#8217;ll take to create one. The steps aren&#8217;t complicated; in fact, they&#8217;re basically the same as the steps you use when creating an HTML page and publishing it to your server.</p>
<p>Unlike creating an HTML page, creating a PHP program requires that you actually work with the source code of the file as opposed to a &#8220;what you see is what you get&#8221; (WYSIWYG) approach. If you&#8217;re used to using a WYSIWYG program (such as Microsoft FrontPage, Macromedia Dream Weaver, or Microsoft Word), it may take you some time to get used to looking at the source code.</p>
<p>The good news is there&#8217;s no reason that you can&#8217;t continue to use a WYSIWYG editor to create an HTML design for your program. However, you may be disappointed to find that many WYSIWYG editors mangle or even delete vital PHP code from your files. For this reason, it is important to find out how your particular editor handles PHP code. If you want to test your WYSIWYG to see how it handles PHP code, create a new file, naming it with a .php extension. Then, switch to your editor&#8217;s source view or open the file in a separate program, such as Notepad and enter the program shown in the first example later in the chapter, making sure not to make any mistakes.</p>
<p>When you&#8217;re finished, save the file and switch back to the WYSIWYG editor. If you see your PHP code, work around it and type a few lines of text. If you want, add some common elements that you include in your Web pages, such as tables and images. Save the file again and close all the open editors.</p>
<p>Now, open the file in Notepad and look at the PHP code. Look for any changes, including changes in the way the code is formatted, special characters that have been converted into codes (such as < to &lt;), and code that has been completely removed.</p>
<p>You will probably find that the PHP code has been changed in some way. Because PHP is sensitive to some of the changes a WYSIWYG editor might make, it's almost impossible to use a WYSIWYG editor once you've started adding PHP code. The PHP community won't tell you that using a WYSIWYG editor is a sign of weakness; doing so can speed things up a lot sometimes.</p>
<p>For now, try using a plain-text editor when you're reading and experimenting with the examples in this book. When you're comfortable with that, feel free to try it with whatever editor you want. By that time, you'll be able to recognize code that the editor has mangled, and you'll have an easier time finding what works best for you.</p>
<p>Regardless of how your current editor handles PHP code, if you are using a WYSIWYG editor, I suggest that you use an editor such as Notepad or one of the many free syntax-highlighting editors out there. Using one of these programs will ensure that your code stays just as you typed it (WYSIWYG editors tend to reformat things as they see fit, which isn't desirable when coding PHP). Even if your editor passed the test, if it's not a strictly text-based (not WYSIWYG) editor, you might find yourself running into problems later.</p>
<p>Here is the process you might use in creating and viewing an HTML file:</p>
<p>Create your HTML file (add text, tables, images, or sounds).</p>
<p>Save your HTML file as filename.html.</p>
<p>Use an FTP program to upload your file to the Web server.</p>
<p>Point your browser to the address of the file on your Web server (for example, http://www.example.com/filename.html).</p>
<p>The process you would use to create a PHP program is much the same:</p>
<p>Create your HTML file (containing text, tables, images, or sounds) and insert PHP code where desired.</p>
<p>Save your PHP file as filename.php.</p>
<p>Use an FTP program to upload your file to the Web server.</p>
<p>Point your browser to the address of the file on your Web server (such as http://www.example.com/filename.php).</p>
<p>The process of creating a PHP program isn't much different from the process you follow to create a regular HTML page.</p>
<p>CAUTION</p>
<p>Many FTP servers (primarily those on Unix-based systems) require you to use a certain FTP "mode": either binary (for images, sounds, and other non-ASCII files) or ASCII (for plain-text files, such as HTML, PHP, and TXT).</p>
<p>Although the FTP transfer appears to be successful, a program transferred in binary mode may not run at all. If this happens, you will receive a "500 Internal Error" response from the server.</p>
<p>Now that you've seen the overall process, let's take a look at our first PHP program. After reading the following example, you'll learn what separates it from a normal HTML file, how to upload it to your Web server, and what the page should look like viewed in your browser.</p>
<pre>
<code>

&lt;!-- File: ch01ex01.php --&gt;
&lt;html&gt;
&lt;head&gt;&lt;title&gt;PHP By Example :: Chapter 1 :: Example 1&lt;/title&gt;&lt;/head&gt;
&lt;body bgcolor="white" text="black"&gt;
&lt;h4&gt;PHP By Example :: Chapter 1 :: Example 1&lt;/h4&gt;
&lt;?php
/* Display a text message */

echo "Hello, world! This is my first PHP program.";

?&gt;

&lt;/body&gt;
&lt;/html&gt;



</code></pre>
<p>This file looks a lot like a regular HTML file. Notice that the file has HTML tags typical of those you would find in any HTML file. In fact, if you disregard everything between the <?php and ?> tags, you might as well rename this file with an .html extension.</p>
<p>However, this file does contain PHP code, so it must be named with a .php extension. The PHP code lies between the PHP tags (<?php and ?>) as shown in Figure 1.1. The command between the PHP tags is echo (PHP&#8217;s word for &#8220;add the following text to the page&#8221;) followed by the text to display. The output, which will be shown soon, looks just as if the text after echo had been in an HTML file itself and no PHP code ever existed.</p>
<p>Figure 1.1. This diagram shows the different parts of a basic PHP program.</p>
<p>Before we look at the output, let&#8217;s upload this file to a Web server and run it. Follow the process outlined previously to write the program, save it as a PHP file (with a .php extension), and upload it to your Web server.</p>
<p>CAUTION</p>
<p>Don&#8217;t forget you shouldn&#8217;t be typing the previous code into a WYSIWYG program such as Microsoft Word or FrontPage. If you do, the code will probably show up in your Web browser just as it appeared previously. Instead, use a plain-text editor such as Notepad.</p>
<p>Once your program is uploaded to your Web server, type its address into your browser. You should get a page back that looks very similar to the screenshot in Figure 1.2.</p>
<p>Figure 1.2. This is what you should see in your browser when you go to the address of your new program.</p>
<p>Programming Syntax<br />
When you accessed the program you just uploaded with your browser, the PHP program went through a process before it was returned to the browser. The process performed the PHP commands within the file; in this case, that was a single echo statement. Figure 1.3 shows what happens when a request is made for a PHP file.</p>
<p>Figure 1.3. Unlike HTML files, PHP files are routed through a special process that performs the PHP commands within the file before it is returned.</p>
<p>The PHP interpreter (or parser) is the program that performs the processing mentioned previously. It reads the PHP program file and executes the commands it understands. (If PHP happens to find a command it doesn&#8217;t understand, it stops parsing the file and sends an error message back to the browser.)</p>
<p>NOTE</p>
<p>Just as &#8220;interpreter&#8221; and &#8220;parser&#8221; are interchangeable terms to refer to the PHP interpreter, &#8220;interprets&#8221; and &#8220;parses&#8221; may be used interchangeably to refer to the process PHP performs when it processes a PHP file.</p>
<p>TIP</p>
<p>If you are an administrator for the Web server you&#8217;re using, you may be interested in knowing that the executable file you installed (a Windows EXE or DLL, or an Apache module or CGI binary on Unix-based systems) is the PHP interpreter.</p>
<p>Every time a request for a particular PHP file is made to a Web server, the PHP interpreter must process the file prior to returning anything to the browser. Because PHP must interpret a PHP program every time that program runs, it is known as a scripting language.</p>
<p>This is quite different from a compiled language, such as C or C++, which is only interpreted from a human-readable form once; a C program is simply translated into machine code (code that is processed directly by the computer&#8217;s processor).</p>
<p>TIP</p>
<p>In a very strict sense, parsing is the process of splitting commands into smaller segments, whereas interpreting is the process of actually comparing those segments to known commands in order to actually perform the correct command.</p>
<p>Since PHP has to interpret the commands included within a program, the commands must be given in such a way that PHP understands them. For example, if someone walked up to you and asked you in German for the time, you probably wouldn&#8217;t know what he was talking about (unless you know German or the person pointed to his wrist). Likewise, if I walked up to you and said, &#8220;Is time it what?&#8221; you probably wouldn&#8217;t know what I was talking about, even though I used English words.</p>
<p>PHP has similar limitations. A statement (the construction of commands and certain characters to make a sentence that PHP will understand) must be given using the correct commands. For example, the command show text has no meaning in PHP; you must instead use a command PHP recognizes, such as echo. Also, just as you must put your words in the correct order to talk to another person in English, you must format the statements you give PHP so that they follow the format PHP expects.</p>
<p>Syntax, then, is the process of putting together statements that PHP will be able to interpret and carry out. Examples of this are PHP&#8217;s opening and closing tags. PHP only parses code that is between PHP tags. Anything else in the file is returned as part of the HTML page, just as seen earlier in the first example.</p>
<p>Here&#8217;s another example. The following statement does not work, even though the command is part of PHP&#8217;s language:</p>
<pre>
<code>

echo "This won't work."

</code></pre>
<p>The statement won&#8217;t work because it doesn&#8217;t follow a basic syntax rule that requires all statements to be terminated with a semicolon. Some special statements must have the semicolon left out, but not many. (The ones that do will be pointed out as we come to them.) For now, just remember that statements should end with a semicolon. The following statement is a corrected version of the preceding line of code:</p>
<pre>
<code>

echo "This works!";


</code></pre>
<p>You may notice that leaving the semicolon off a single statement doesn&#8217;t cause PHP to display an error message. This is a feature of PHP to make it easier to insert a single echo statement. To see the error when you try to run the first echo statement, copy the statement to two separate lines so it looks like this:</p>
<pre>
<code>


echo "This won't work."
echo "This won't work."


</code></pre>
<p>The code will not run and PHP will return an error because there isn&#8217;t a semicolon separating the statements.</p>
<p>Good Style: Using Whitespace and Comments<br />
You may be curious why PHP requires a semicolon at the end of every statement. The answer is that semicolons allow other aspects of PHP code to be more flexible. By signaling the end of a command with a semicolon instead of a new line, new lines can be added or taken out of the code without affecting the code itself. In fact, new lines are only a portion of what can be changed without changing what the interpreter sees when it processes the file.</p>
<p>Whitespace— all spaces, tabs, and line breaks—is left to be used at the discretion and preference of the programmer. This may seem trivial at first, but think about the difference the indentation in an outline makes; the indentation divides topics into subtopics and even subtopics under the subtopics into separate sections. Take a look at the following example, which contains no whitespace.</p>
<pre>
<code>


&lt;?php
/* ch01ex02.php – an example of code with no whitespace */
echo"Hithere.";echo"Thisprogramhasnowhitespace";echo"It'salmostimpossibletoread.";
?&gt;



</code></pre>
<p>NOTE</p>
<p>Although the line with all of the echo statements contains no whitespace, the program file as a whole does. The line breaks have been left to separate the PHP tags, the comment, and all the echo statements so at least the purpose of the program is easily decipherable.</p>
<p>You can see how hard it would be to read line after line of code like that. This code should be split into separate lines, with one for each echo statement.</p>
<p>By placing curiouscode on the same line, a new line, or a few blank lines apart, a programmer can group certain parts of his code together and separate other parts. This helps him keep up with how he divided a certain task into smaller, simpler tasks.</p>
<p>Spaces or tabs can be used in PHP to create the same kind of clarity and organization found in an outline as mentioned before. The following example demonstrates this principle:</p>
<pre>

<code>

&lt;?php
/* ch01ex03.php – program to show usefulness of indenting */

if ($gotPHP) {
echo "Got PHP?";

if ($PHPMustache) {
echo " :)";
}
}

?&gt;


</code></pre>
<p>Even though you haven&#8217;t really learned anything about the statements this program uses, you can easily see how everything follows a form similar to that of an outline. Also, the separation of</p>
<pre>
<code>

echo "Got PHP?";

and

if ($PHPMustache) {

by a blank line signifies that the statements serve two different purposes.
</code></pre>
<p>As you curiousread this book, keep whitespace in mind. Think about what makes code easy to understand or hard to understand. Read the statements in each example as it is presented and then go back and look at how it&#8217;s formatted. Good style in coding PHP is just as important as knowing the syntax; if your code is formatted into logical sets of statements, no one will have to break it down on his own as he reads it.</p>
<p>The other curiousvery useful element of style is commenting. Comments are descriptions, notes, and other information enclosed in a special character sequence that tells the parser to ignore whatever is within. Therefore, comments are treated the same way as whitespace; they are completely ignored by PHP.</p>
<p>Comments can be done either of two ways: single line or multiline. The one you pick depends on what you want to comment out. The following example is a file header using multiline comments that might be found in a PHP program file:</p>
<pre>
<code>


&lt;?php
/*
All this is comments+-------------------------------------------------+ */

echo "This is Example_Program 1.0";

?&gt;


</code></pre>
<p>As demonstrated in this example, to create a multiline comment, the programmer must enclose all of his comment text within /* and */.</p>
<p>TIP</p>
<p>Multiline comments can be used to comment out a block of code you don&#8217;t want PHP to evaluate. Simply place a /* before the code and a */ after the code and PHP will ignore it.</p>
<p>The other comments that are available are single-line comments. These comments are used to comment out everything from the comment marker, which is //, to the end of the line.</p>
<p>CAUTION</p>
<p>Although single-line comments may appear within a block of commented-out code, multiline comments are not allowed within multiline comments. Doing so would cause PHP to stop ignoring the commented text immediately after the first */ instead of after the second one, as the programmer intends.</p>
<p>You can find a few different examples of single line comments in the following code:</p>
<pre>
<code>

&lt;?php
// File: example_file.php

echo "This is an example file!"; // Show some text

/* Don't plead insanity anymore

// Plead insanity
echo "This program did not consciously commit the crime, therefore it pleads insanity.";
*/

?&gt;
</code></pre>
<p>The first comment found is a very short file header that tells the file&#8217;s name. Following it there is a comment describing the action taken by the first echo command. Comments such as this can help clarify things, but use them with discretion. The comment has no good use in this case because it doesn&#8217;t say anything we can&#8217;t pick up directly from the statement. Generally, use a comment if you (or someone else who might read your code) don&#8217;t immediately understand the code when you look at it.</p>
<p>Following that we have a multiline comment that is commenting out a block of code that we wanted to stop from being processed by PHP. PHP will therefore ignore the last echo statement. Notice that it&#8217;s perfectly legal to have a single-line comment within multiline comments.</p>
<p>Take note of how comments are used and make use of them in your own code. It&#8217;s much easier to read a comment and know what something does rather than having to read the code and figure it out step-by-step. With that in mind, use comments liberally to explain what your programs are doing.</p>
<p>How Embedded Programming Works<br />
Before now, I&#8217;ve only mentioned that PHP code must be enclosed in the <?php and ?> PHP tags. Using tags to separate PHP code and HTML code within the same file allows programming code to be mixed directly with information that is going to be sent to the browser just as it is. This makes PHP an embedded programming language because PHP code is embedded directly in HTML code.</p>
<p>This concept is relatively new: Before languages like PHP, programs had no real need to display data using a structured formatting language as complex as HTML. Information displayed on the screen was usually just letters, numbers, and spaces, without many colors, sizes, or other formatting markups.</p>
<p>Since PHP was made for Web programming, it is intended to be used with HTML, which significantly increases the amount of information that has to be sent back to the browser. Not only does PHP have to send back the information the user sees, but also the markup tags required to format the information correctly.</p>
<p>To make the mixing of information and markup tags simpler, PHP code is embedded directly in the HTML page where the information is desired. The example at the beginning of this chapter demonstrates this concept quite clearly; the program is mostly regular HTML code, but PHP is also used to insert some information.</p>
<p>Embedded programming will make your job as a programmer much easier; you can add programming where you need it and use regular HTML the rest of the time. However, be sure to enclose your PHP code in PHP tags or your code will not be parsed, but rather displayed on the HTML page.</p>
<p>The following program provides another example of embedded programming:</p>
<pre>
<code>

&lt;?php
/* File: hello_world.php – displays "Hello, World!" */
?&gt;

&lt;html&gt;
&lt;head&gt;&lt;title&gt;Hello, World!&lt;/title&gt;&lt;/head&gt;
&lt;body bgcolor="white" text="black"&gt;

Hello,
&lt;?php
// Send "World!" to the visitor's browser
echo "World!";
?&gt;

&lt;/body&gt;
&lt;/html&gt;

</code></pre>
<p>When this file is accessed through a Web server, the PHP interpreter will process the file line by line from the top to bottom. Thus, the information before the opening PHP tag is sent to the browser, along with the result of the echo statement. The Web browser receives an HTML file that looks like this:</p>
<pre>
<code>

&lt;html&gt;
&lt;head&gt;&lt;title&gt;Hello, World!&lt;/title&gt;&lt;/head&gt;
&lt;body bgcolor="white" text="black"&gt;

Hello, World!

&lt;/body&gt;
&lt;/html&gt;

</code></pre>
<p>The browser then displays the file just as it would any other HTML file.</p>
<p>TIP</p>
<p>As mentioned before, a single echo statement doesn&#8217;t have to be terminated with a semicolon to be understood by PHP. However, you may want to come back and add more statements later. For this reason, it&#8217;s a good idea to consistently include the semicolon, regardless of its necessity.
</p>
]]></content:encoded>
			<wfw:commentRSS>http://www.kekh.com/chapter-1/writing-a-basic-php-program/feed/</wfw:commentRSS>
		</item>
		<item>
		<title>Server-Side Versus Client-Side Scripting</title>
		<link>http://www.kekh.com/chapter-1/server-side-versus-client-side-scripting/</link>
		<comments>http://www.kekh.com/chapter-1/server-side-versus-client-side-scripting/#comments</comments>
		<pubDate>Wed, 23 Aug 2006 20:34:04 +0000</pubDate>
		<dc:creator><ADMINNICENAME></dc:creator>
		
	<category>Chapter 1</category>
		<guid isPermaLink="false">http://kekh.com/chapter-1/server-side-versus-client-side-scripting/</guid>
		<description><![CDATA[As already explained, PHP code is processed at the Web server before anything is returned to the browser. This is referred to as server-side processing. Most Web programming works this way: PHP, ASP, Perl, C, and others.
However, a few languages are processed by the browser after it receives the page. This is called client-side processing. [...]]]></description>
			<content:encoded><![CDATA[<p>As already explained, PHP code is processed at the Web server before anything is returned to the browser. This is referred to as server-side processing. Most Web programming works this way: PHP, ASP, Perl, C, and others.</p>
<p>However, a few languages are processed by the browser after it receives the page. This is called client-side processing. The most common example of this is JavaScript.</p>
<p>TIP</p>
<p>Despite the similarity in their names, Java and JavaScript are far from being the same. Many Web developers are familiar with JavaScript, but this does not make them Java programmers. It&#8217;s important to remember that these languages are not the same.</p>
<p>This can lead to an interesting problem with logic. The following example demonstrates what I mean:</p>
<pre>
<code>

&lt;script language="JavaScript"&gt;

if (testCondition())
{
&lt;?php
echo "&lt;b&gt;The condition was true!&lt;/b&gt;";
?&gt;
} else {
&lt;?php
echo "&lt;b&gt;The condition was not true.&lt;/b&gt;";
?&gt;
}

&lt;/script&gt;


</code></pre>
<p>Many times the programmer of such a segment expects only one of the echo statements to execute. However, both will execute, and the page will be left with JavaScript that will generate errors (because the information in the echo statements is not valid JavaScript code). If this is a little unclear, read on; the following demonstration should clear things up for you.</p>
<p>NOTE</p>
<p>If you&#8217;re not familiar with JavaScript, don&#8217;t worry. The important concept behind this discussion is that PHP, being a server-side language, will be evaluated before the JavaScript, which is a client-side language. This won&#8217;t be an issue if you don&#8217;t use a client-side scripting language like JavaScript.</p>
<p>The resulting code from the previous snippet follows; notice that the JavaScript has been left intact and untouched, but the PHP code has been evaluated. PHP ignores the JavaScript code completely:</p>
<pre>
<code>

&lt;script language="JavaScript"&gt;

if (testCondition())
{
&lt;b&gt;The condition was true!&lt;/b&gt;
} else {
&lt;b&gt;The condition was not true.&lt;/b&gt;
}

&lt;/script&gt;


</code></pre>
<p>As you can see, this code will cause JavaScript errors when executed. Be cautious when combining PHP and JavaScript code: It can be done, but it must be done with attention to the fact that the PHP will always be evaluated without regard for the JavaScript. To successfully combine the two, it&#8217;s generally necessary to output JavaScript code with PHP.</p>
<p>The following example does just that:</p>
<pre>
<code>

&lt;script language="JavaScript"&gt;

if (testCondition())
{
&lt;?php
echo "document.write('&lt;b&gt;The condition was true!&lt;/b&gt;');";
?&gt;
} else {
&lt;?php
echo "document.write('&lt;b&gt;The condition was not true.&lt;/b&gt;');";
?&gt;
}

&lt;/script&gt;

</code></pre>
<p>As you can see, doing this gets complicated very quickly, so it&#8217;s best to avoid combining PHP and JavaScript. However, the resulting code below shows you that this will work.</p>
<pre>
<code>
&lt;script language="JavaScript"&gt;

if (testCondition())
{
document.write('&lt;b&gt;The condition was true!&lt;/b&gt;');
} else {
document.write('&lt;b&gt;The condition was not true.&lt;/b&gt;');
}

&lt;/script&gt;

</code></pre>
]]></content:encoded>
			<wfw:commentRSS>http://www.kekh.com/chapter-1/server-side-versus-client-side-scripting/feed/</wfw:commentRSS>
		</item>
		<item>
		<title>Running Your New Program</title>
		<link>http://www.kekh.com/chapter-1/running-your-new-program/</link>
		<comments>http://www.kekh.com/chapter-1/running-your-new-program/#comments</comments>
		<pubDate>Tue, 22 Aug 2006 20:35:40 +0000</pubDate>
		<dc:creator><ADMINNICENAME></dc:creator>
		
	<category>Chapter 1</category>
		<guid isPermaLink="false">http://kekh.com/chapter-1/running-your-new-program/</guid>
		<description><![CDATA[Following the same procedure outlined at the beginning of this chapter, try running this program.
If your program doesn&#8217;t display &#8220;Hello, World!&#8221; in your browser, go through the next section and try to eliminate reasons why the program might not run.
TIP
A good directory structure should use general categories and narrow those categories through subdirectories. Such a [...]]]></description>
			<content:encoded><![CDATA[<p>Following the same procedure outlined at the beginning of this chapter, try running this program.</p>
<p>If your program doesn&#8217;t display &#8220;Hello, World!&#8221; in your browser, go through the next section and try to eliminate reasons why the program might not run.</p>
<p>TIP</p>
<p>A good directory structure should use general categories and narrow those categories through subdirectories. Such a directory structure, if followed consistently, will keep you from ever searching for a file. You will be able to find a file in less than thirty seconds every time.</p>
<p>Mirroring your directory structure on your Web server is also a good sign of organization. The idea is to create a &#8220;web root&#8221; folder on your hard drive and have it mirror the root public directory on your Web server. Doing this enables you to transfer a copy of your whole Web site between your server and hard drive without worrying about the files being organized differently.</p>
<p>What If It Didn&#8217;t Work?<br />
There are quite a few things that could be going wrong, but this section provides a comprehensive list of reasons why your program may not be running. The following is a list of things that might have gone wrong; find the one that describes the behavior of your problem and jump ahead to the appropriate heading.</p>
<p>A Save As dialog box appears.</p>
<p>The page comes up, but the PHP code doesn&#8217;t appear to have executed.</p>
<p>The PHP code appears directly in the browser.</p>
<p>A &#8220;404 File Not Found&#8221; or a &#8220;CGI Error—The specified CGI application misbehaved by not returning a complete set of HTTP headers&#8221; message appears.</p>
<p>A &#8220;Parse error&#8221; message appears.</p>
<p>A Save As Dialog Box Appears<br />
If this occurs, PHP is not installed correctly or the file is misnamed. It occurs because the Web server doesn&#8217;t recognize the file as a PHP file, but rather as an unknown file type. Since most unknown file types (Zip files, for example) are to be downloaded and not processed, the server is sending the file just as it is to be downloaded by the browser. This surely isn&#8217;t the behavior we want.</p>
<p>To fix this, first check to make sure you named your file with a .php extension. If you didn&#8217;t, rename it with the Rename command in your FTP client. If you chose to rename the copy on your local hard drive, make sure you transfer the file to the server. Try accessing the page again and see if the problem is solved; if not, repeat the process with .php3, .php4, and .phtml.</p>
<p>It is very possible that none of those will work. In that case, the problem is most likely that your Web server doesn&#8217;t have PHP installed or PHP is configured incorrectly. Get in touch with the server administrator to find out if PHP is installed, and, if so, what the correct extension is. If the extension is one that you&#8217;ve already tried, explain to the administrators that the extension isn&#8217;t working and see if they can help you find out why.</p>
<p>If you are your server administrator, you may need help with checking your configuration; first check the PHP manual (http://www.PHP.net/manual/). If you still have trouble, you may find help on the PHP installation mailing list. Send an email to php-install@lists.php.net including information about your server such as operating system, Web server, and the version of PHP you&#8217;re trying to install. The list members will be happy to help.</p>
<p>The PHP Code Doesn&#8217;t Appear to Have Executed<br />
If this is the case, you will see only the parts of the page that were outside of the PHP tags. Specifically, you will see &#8220;Hello,&#8221; printed on the page, but &#8220;World!&#8221; will be missing. If you use your browser&#8217;s View Source command, you will notice that the PHP code appears in your HTML source just like it did in your editor. This means that the file was returned just like a normal HTML file (without any server-side processing).</p>
<p>Check to make sure that your file is named with an appropriate extension (such as .php); this is the most common reason the PHP code wouldn&#8217;t execute.</p>
<p>If that fails, read through the section describing what to do if the Save As dialog box appeared; the problem must be that .php isn&#8217;t associated with PHP in the Web server&#8217;s configuration. That section will help you straighten out your Web server&#8217;s configuration.</p>
<p>The PHP Code Appears Directly in the Browser<br />
This is because you entered the code into a WYSIWYG editor such as FrontPage or DreamWeaver. As you entered the code, the editor converted key parts of it (such as the <?php tag) into text using HTML special character codes (so, the result would be &lt;?php). Although you see <?php in your browser, if you look at the source code (using your browser&#8217;s View Source command), you will notice that the version with the special character codes is used.</p>
<p>To correct this, enter the code in a text-only editor, such as Notepad or PHPEd. (See Appendix A for more information about editors.)</p>
<p>A &#8220;404 File Not Found&#8221; or &#8220;CGI Error&#8221; Message Appears<br />
The first of these may seem obvious, but it&#8217;s not always so obvious if you use Notepad to create your PHP file. One of the problems with using Notepad is its preference for .txt extensions; even if you give your file a .php extension, Notepad adds a .txt.</p>
<p>When the Web server tries to find the .php file you requested, the file isn&#8217;t there because it&#8217;s really named .php.txt. In most cases, the server would then return a &#8220;404 File Not Found&#8221; error, but if PHP is installed as a CGI filter, you might get the latter message about incomplete HTTP headers being returned.</p>
<p>In either case, rename the file to .php and try again.</p>
<p>A &#8220;Parse Error&#8221; Message Appears<br />
This message, mentioned briefly before, means PHP doesn&#8217;t know how to interpret something inside of the PHP tags. This isn&#8217;t at all uncommon.</p>
<p>For the example shown previously, it probably means you mistyped something. Go back and check to make sure the files match exactly, line for line. Check to ensure that the same quotes are used (double quotes are not the same as two single quotes).</p>
<p>The parse error will be accompanied by a helpful message explaining exactly why your program isn&#8217;t running. Check the line that PHP mentions for possible errors, and then check the lines around it.
</p>
]]></content:encoded>
			<wfw:commentRSS>http://www.kekh.com/chapter-1/running-your-new-program/feed/</wfw:commentRSS>
		</item>
		<item>
		<title>What&#8217;s next</title>
		<link>http://www.kekh.com/chapter-1/whats-next/</link>
		<comments>http://www.kekh.com/chapter-1/whats-next/#comments</comments>
		<pubDate>Mon, 21 Aug 2006 20:36:18 +0000</pubDate>
		<dc:creator><ADMINNICENAME></dc:creator>
		
	<category>Chapter 1</category>
		<guid isPermaLink="false">http://kekh.com/chapter-1/whats-next/</guid>
		<description><![CDATA[You should now have a clear understanding of how PHP processes  a PHP file. You should also have a basic understanding of PHP&#8217;s syntax,  including how to use the PHP tags, how and when to use comments, and the  importance of statement termination with semicolons.
In the next chapter, you will begin with [...]]]></description>
			<content:encoded><![CDATA[<p class="docText">You should now have a clear understanding of how PHP processes  a PHP file. You should also have a basic understanding of PHP&#8217;s syntax,  including how to use the PHP tags, how and when to use comments, and the  importance of statement termination with semicolons.</p>
<p class="docText">In the next chapter, you will begin with discussions of  variables, variable types, and constants. With this new knowledge, you will be  able to store any information you want in the computer&#8217;s memory in order to  manipulate it and send the results back to the browser, which we will discuss in  the coming chapters.</p>
]]></content:encoded>
			<wfw:commentRSS>http://www.kekh.com/chapter-1/whats-next/feed/</wfw:commentRSS>
		</item>
		<item>
		<title>Variables and Constants</title>
		<link>http://www.kekh.com/chapter-2/variables-and-constants/</link>
		<comments>http://www.kekh.com/chapter-2/variables-and-constants/#comments</comments>
		<pubDate>Mon, 31 Jul 2006 20:38:45 +0000</pubDate>
		<dc:creator><ADMINNICENAME></dc:creator>
		
	<category>Chapter 2</category>
		<guid isPermaLink="false">http://kekh.com/chapter-2/variables-and-constants/</guid>
		<description><![CDATA[Now that you know the basics of creating a PHP program, it&#8217;s time to learn about all the things a program can do. Essentially, all programs exchange and manipulate data. For example, the information from a Web site&#8217;s feedback form might be collected and sent via e-mail to the Webmaster. The data from the form [...]]]></description>
			<content:encoded><![CDATA[<p>Now that you know the basics of creating a PHP program, it&#8217;s time to learn about all the things a program can do. Essentially, all programs exchange and manipulate data. For example, the information from a Web site&#8217;s feedback form might be collected and sent via e-mail to the Webmaster. The data from the form would be stored in variables, which could then be used to send the form data in an e-mail.</p>
<p>Thus, you have seen one basic use for variables and constants. Any data that a program works with is stored in variables and constants. So, as we explore the way your program will work with data in this chapter and the chapters ahead, we&#8217;ll start with variables and constants, the storage units for all data.</p>
<p>This chapter teaches you the following:</p>
<p>How to declare variables and constants</p>
<p>Naming techniques</p>
<p>Types and type casting</p>
<p>Scope</p>
<p>References
</p>
]]></content:encoded>
			<wfw:commentRSS>http://www.kekh.com/chapter-2/variables-and-constants/feed/</wfw:commentRSS>
		</item>
		<item>
		<title>Introduction to Variables and Constants</title>
		<link>http://www.kekh.com/chapter-2/introduction-to-variables-and-constants/</link>
		<comments>http://www.kekh.com/chapter-2/introduction-to-variables-and-constants/#comments</comments>
		<pubDate>Mon, 31 Jul 2006 20:37:31 +0000</pubDate>
		<dc:creator><ADMINNICENAME></dc:creator>
		
	<category>Chapter 2</category>
		<guid isPermaLink="false">http://kekh.com/chapter-2/introduction-to-variables-and-constants/</guid>
		<description><![CDATA[A program contains two basic things: commands and values. The commands all have certain tasks they perform; the values are the information that the tasks are performed with. Until now, all your programs have used literal values; that is, any time a value has been specified, it has been hard coded into the program.
For example, [...]]]></description>
			<content:encoded><![CDATA[<p>A program contains two basic things: commands and values. The commands all have certain tasks they perform; the values are the information that the tasks are performed with. Until now, all your programs have used literal values; that is, any time a value has been specified, it has been hard coded into the program.</p>
<p>For example, take a look at an echo statement found in Chapter 1, &#8220;Welcome to PHP&#8221;:</p>
<pre><code>

echo "World!";

</code></pre>
<p>This statement performs the echo command (which we know inserts text) using the literal value given after it (&#8221;World!&#8221;).</p>
<p>NOTE</p>
<p>A literal is a value that you give explicitly within a program. For example, 5, 5.5, and &#8220;World!&#8221; are all literals.</p>
<p>The point of a program isn&#8217;t to say &#8220;World!&#8221; all the time. That could be accomplished with a regular HTML page. The whole point of writing a program is to have a uniform task performed with whatever information is specified. For example, you might want it to be able to say &#8220;Earth&#8221; instead of &#8220;World.&#8221;</p>
<p>Let&#8217;s consider what you&#8217;re planning to do. You know the program should output something, either way. Thus, you know you want the program to do something like this:</p>
<p>echo something;</p>
<p>You just don&#8217;t know what something is. To specify what something is, use a variable. A variable is a name that represents a value. The value of a variable may change throughout a program, or it may stay the same once it&#8217;s set.</p>
<p>For example, you might use a variable called $strText to insert whatever text is being used for a particular execution of the program.</p>
<p>NOTE</p>
<p>The name $strText is preceded by a dollar sign because that&#8217;s how PHP recognizes it as a variable.</p>
<p>Also, if you&#8217;re curious, the str prefix is an abbreviation for &#8220;string&#8221; (the type of data will be character string); it&#8217;s purpose is a matter of style, only.</p>
<p>Don&#8217;t worry about it right now; we&#8217;ll discuss data types and style conventions related to variables later in this chapter.</p>
<p>The following program uses the variable $strText, instead of a literal:</p>
<pre><code>



TIP

For now, don't be too distracted by the line that says:

$strText = $HTTP_GET_VARS['strText'];

</code></pre>
<p>This statement takes whatever value is specified in the URL and stores it in $strText; since it&#8217;s more related to program input, we won&#8217;t discuss it further until Chapter 3, &#8220;Program Input and Output (I/O).&#8221;</p>
<p>Try running this program with the following URLs (replacing www.example.com/path/ with the appropriate address for this program):</p>
<p>http://www.example.com/path/ch02ex01.php?strText=World</p>
<p>http://www.example.com/path/ch02ex01.php?strText=Earth</p>
<p>http://www.example.com/path/ch02ex01.php?strText=PHP%20Programmer</p>
<p>The output changes each time you run the program, depending on what URL you specify. Although this program is very basic, it shows the definite usefulness of variables.</p>
<p>TIP</p>
<p>The URLs shown aren&#8217;t as complex as they might seem; we&#8217;ll pick these apart and discuss them in Chapter 3. For now, notice that in each URL, a different value is specified for strText, and when you enter each URL, the program displays the corresponding value.</p>
<p>It is important to note that although variables and constants serve the same purpose, they aren&#8217;t at all identical.</p>
<p>Whereas, the value of a variable might change any number of times throughout the execution of a program, constants are values that will never change (and in fact can&#8217;t change) during the execution of the program.</p>
<p>Constants are often used to set program options. For instance, a constant named DEBUG might be used to determine how much information should be given to the visitor if something goes wrong—either a simple error message to tell the visitor there&#8217;s a problem or a detailed error message to help the programmer resolve problems within the script.
</p>
]]></content:encoded>
			<wfw:commentRSS>http://www.kekh.com/chapter-2/introduction-to-variables-and-constants/feed/</wfw:commentRSS>
		</item>
		<item>
		<title>Declaration and Assignment</title>
		<link>http://www.kekh.com/chapter-2/declaration-and-assignment/</link>
		<comments>http://www.kekh.com/chapter-2/declaration-and-assignment/#comments</comments>
		<pubDate>Sat, 29 Jul 2006 22:17:29 +0000</pubDate>
		<dc:creator><ADMINNICENAME></dc:creator>
		
	<category>Chapter 2</category>
		<guid isPermaLink="false">http://www.kekh.com/chapter-2/declaration-and-assignment/</guid>
		<description><![CDATA[Declaration is the term used to describe the creation of a variable or constant. Assignment, which is covered in the following sections, is the process of storing a value in a variable.
Declaring Variables
Declaring a variable is quite simple—all you have to do is assign something to it. If, for example, you wish to assign the [...]]]></description>
			<content:encoded><![CDATA[<p>Declaration is the term used to describe the creation of a variable or constant. Assignment, which is covered in the following sections, is the process of storing a value in a variable.</p>
<p>Declaring Variables<br />
Declaring a variable is quite simple—all you have to do is assign something to it. If, for example, you wish to assign the number five to a variable named $intFive, you would use the following:</p>
<pre><code>

$intFive = 5;

</code></pre>
<p>The dollar sign in the variable name isn&#8217;t part of the variable name, per se. Instead, it&#8217;s how PHP knows you&#8217;re referring to a variable named intFive. Whenever you use a variable, you must precede it with a dollar sign.</p>
<p>Variable names in PHP must follow the following requirements:</p>
<p>Any combination of letters, numbers, and underscores can be used.</p>
<p>Names can be as short as one character and can be of any length.</p>
<p>Names can begin only with a letter or an underscore; variable names cannot begin with a number.</p>
<p>As you already know, just because PHP understands a variable following the requirements seen previously doesn&#8217;t mean you and the people who read your code will. To improve style, variables should be named according to these style guidelines:</p>
<p>Keep variable names meaningful. For example, don&#8217;t use $x to store a visitor&#8217;s age; instead, use $intVisitor_age.</p>
<p>If you come back to make changes or fixes in your program a month from when you first write it, you will be confused with variable names like $x because $x doesn&#8217;t mean anything, whereas $intVisitor_age says exactly what it contains.</p>
<p>Variable names should be reasonably short. Typing a 25-character variable name just a few times will become a bit tedious and frustrating. Try abbreviating; just be sure your abbreviation makes sense.</p>
<p>For example, instead of $strWebPageFormFieldForEmailAddress, it would obviously be just as clear if it were named $strVisitor_Email.</p>
<p>Prefix a variable type abbreviation to the variable name. Although variable types are explained a little later in the chapter, you should recognize now that the variables suggested so far in this list have been preceded by int or str.</p>
<p>All variables should be prefixed as follows: int for integers, flt or dbl for floating-point numbers or doubles, str for strings, and arr for arrays.</p>
<p>Format your variable names in a hierarchical fashion, separating major divisions with underscores. For example, if you have a visitor&#8217;s first name, last name, and e-mail address, it&#8217;s better to use $strVisitor_first, $strVisitor_last, and $strVisitor_email instead of $strFirstName, $strLastName, and $strEmail because you may find later in the script that you want to refer to another e-mail address or another person&#8217;s name. Although the underscore-divided names are a little bit longer, it&#8217;s worth it to keep conflicts and confusion from arising later in the script. You don&#8217;t want to find yourself asking, &#8220;Whose e-mail do I have in $strEmail?&#8221;</p>
<p>Following these conventions makes your programs easier to understand to anyone that has to work with them, especially you.</p>
<p>Assigning Variables<br />
There are two ways a variable can be assigned: in the script itself, or by the PHP interpreter. For now, let&#8217;s focus on variables that are created (declared and assigned) by the script itself. Variables assigned automatically by the PHP interpreter (such as the $HTTP_GET_VARS variable found in the first example of this chapter), will be discussed in Chapter 3.</p>
<p>Assignment, as you&#8217;ve already learned, occurs when a value is stored in a variable. Whenever you assign a value to a variable, you must keep in mind the order in which the assignment will be processed. For example, the following two statements are not equivalent:</p>
<pre><code>

$intFive = 5;
5 = $intFive;

</code></pre>
<p>As a rule of thumb, read assignments from right to left—the first would read, &#8220;the number 5 should be assigned to the variable $intFive.&#8221; Reading assignments in this fashion will become more and more important as your programs and statements grow in complexity.</p>
<p>Now, take a look at the second assignment—&#8221;the variable $intFive should be assigned to the number 5.&#8221; The latter doesn&#8217;t make sense; it will definitely not work. In fact, if you were to use this statement in a program, PHP would stop with a parse error.</p>
<p>Declaring a Constant<br />
Declaring a constant is done using the define function (more will be discussed about functions in Chapter 11, &#8220;Classes and Objects&#8221;). The following example demonstrates the declaration of a constant, EXAMPLE, with a value of 5:</p>
<pre><code>



</code></pre>
<p>Notice that EXAMPLE is not preceded by a dollar sign in either statement. The dollar sign is reserved for use only with variables; constants should never be preceded by a dollar sign.</p>
<p>Just as variables have naming requirements that must be followed, so do constants. The following guidelines will ensure that you always use a valid name for a constant:</p>
<p>A constant&#8217;s name should not be preceded by a dollar sign.</p>
<p>The name should begin with a letter or underscore, but never a number.</p>
<p>Constants cannot be redefined; that is, the value of EXAMPLE cannot be changed after it has already been defined. After all, that&#8217;s why it&#8217;s defined as a constant instead of a variable.</p>
<p>As with variables, constants should also be subject to naming conventions for clarity and good style. Adhered to consistently, the following guidelines improve the style of your code:</p>
<p>Keep names short enough to be convenient. This rule is followed less strictly than most; because constants are generally only used for setting options, they aren&#8217;t usually mentioned as frequently as variables. Therefore, it&#8217;s generally acceptable to make a constant&#8217;s name longer.</p>
<p>Constants should always be named using all uppercase. This helps distinguish that you&#8217;re intentionally using the word without quotes. Thus, as soon as you see a word in your program written in all caps, you know you can probably look for a constant being defined with that name.</p>
<p>Separate words with underscores. Since constants don&#8217;t have the ability to switch case (capitalizing the first letter of every word and using lowercase for the rest), underscores are necessary to keep the separate words in a name easily distinguishable.</p>
<p>Name constants in a hierarchical fashion. As with variables, if you have several constants that are related in some way (they all describe the program, for instance), it would be good to prefix them with PROGRAM. Thus, you&#8217;ll end up with PROGRAM_VERSION, PROGRAM_AUTHOR, and PROGRAM_LAST_UPDATE, which are a lot less ambiguous than VERSION, AUTHOR, and LAST_UPDATE, which could describe a number of different things.</p>
<p>Also, by using a hierarchical form (as opposed to just separating words, which would lead to names like PROGRAM_VERSION and LAST_PROGRAM_UPDATE), the constants are grouped into a related set. Because they all begin with PROGRAM_, we know they&#8217;re related. If, however, we used a name such as LAST_PROGRAM_UPDATE, although it is clear, we don&#8217;t know just from looking at it that it is related to the other two constants.</p>
<p>NOTE</p>
<p>Although a variable type prefix is very useful in variables, it isn&#8217;t necessary in constants. The purpose and type of a constant never change (and can&#8217;t change), so it&#8217;s safe to assume that a variable is whatever type it is defined to be when it&#8217;s first defined.</p>
<p>TIP</p>
<p>It&#8217;s a good idea to define all constants at the beginning of your program. If you get halfway through and need to define another constant, scroll back up and put it at the top of the file instead of just putting it wherever you currently are in the program. This will make it much easier to find out what the value of the constant is; looking through hundreds of lines of code in multiple files is quite a task if constants aren&#8217;t defined at the top of the program.</p>
<p>Deciding Whether to Use a Variable or Constant<br />
If you find wondering whether to use a variable or a constant, think about how the information will be needed within the program.</p>
<p>If the value might be modified sometime during the program&#8217;s execution, always use a variable. Using a constant completely prevents the value being modified.</p>
<p>Conversely, if you want to intentionally keep a value from being modified, use a constant. This is a built-in feature of the language so you can protect certain values from accidentally being changed, either by you or by another programmer who isn&#8217;t as familiar with your program.</p>
<p>If you&#8217;re not sure whether to use a variable or a constant, use a variable. If you use a variable where a constant might have been a better choice, it&#8217;s not really a big problem; however, if you use a constant where a variable would have been better, changing it to a variable throughout the script can give you quite a headache.</p>
<p>Related:</p>
<p><a href="http://www.phptutor.info/php-tutorials.php">More PHP Tutorials</a>
</p>
]]></content:encoded>
			<wfw:commentRSS>http://www.kekh.com/chapter-2/declaration-and-assignment/feed/</wfw:commentRSS>
		</item>
		<item>
		<title>Variable Types</title>
		<link>http://www.kekh.com/chapter-2/variable-types/</link>
		<comments>http://www.kekh.com/chapter-2/variable-types/#comments</comments>
		<pubDate>Fri, 28 Jul 2006 22:21:28 +0000</pubDate>
		<dc:creator><ADMINNICENAME></dc:creator>
		
	<category>Chapter 2</category>
		<guid isPermaLink="false">http://www.kekh.com/chapter-2/variable-types/</guid>
		<description><![CDATA[Variable types, which are handled automatically by PHP, tell PHP what kind of value it&#8217;s working with. To put things in perspective, think about what you know about certain values. Cat, for example, is text. You can&#8217;t multiply cat by cat because they&#8217;re not numbers, they&#8217;re text. However, 5 and 5 can be multiplied to [...]]]></description>
			<content:encoded><![CDATA[<p>Variable types, which are handled automatically by PHP, tell PHP what kind of value it&#8217;s working with. To put things in perspective, think about what you know about certain values. Cat, for example, is text. You can&#8217;t multiply cat by cat because they&#8217;re not numbers, they&#8217;re text. However, 5 and 5 can be multiplied to make 25. They&#8217;re numbers, so it works.</p>
<p>PHP recognizes a value as belonging to a certain data type depending on the characteristics of the value. The following sections describe certain characteristics and behaviors for each data type.</p>
<p>Integers<br />
An integer is any numeric value that does not have a decimal point, such as the following:</p>
<p>5 (five)</p>
<p>–5 (negative five)</p>
<p>0123 (preceded by a zero; octal representation of decimal number 83)</p>
<p>0&#215;12 (preceded by 0x; hexadecimal representation of decimal number 18)</p>
<p>The last two values on the list are somewhat advanced topics and are rare. They are presented for your information so you know what you&#8217;re dealing with if you ever encounter this notation. It is important, however, for you to know that preceding a number with a zero (which may seem insignificant) is going to produce unexpected results. The previous example, for instance, proves this point: 123 is much different than 83 (which is 0123 octal).</p>
<p>NOTE</p>
<p>PHP does have limitations within the integer type. On 32-bit platforms, integers are limited to be 32-bit numbers (–2,147,483,648 to 2,147,483,648); on 64-bit platforms integers are limited to be 64-bit numbers (–9,223,372,036,854,775,808 to 9,223,372,036,854,775,808). This generally doesn&#8217;t become a problem, but if you attempt to handle extremely large values (negative or positive), you might find that results aren&#8217;t as expected. This is a limitation of all programming languages and there is information on the PHP Web site for using larger numbers, should you have the need.</p>
<p>Floating-Point Numbers<br />
A floating-point number (commonly referred to simply as a float or double, which, in PHP, are exactly the same thing) is a numeric value with a decimal point.</p>
<p>The following are all floating-point values:</p>
<p>5.5</p>
<p>.055e2 (scientific notation for .055 times 10 to the second power, which is 5.5)</p>
<p>19.99</p>
<p>The second example is a float represented in scientific notation. The e, as is often the case on graphing calculators, means &#8220;times 10 to the&#8221;. It is followed by whatever power 10 should be raised to in order to put the decimal wherever you want it. Thus, .055e2 is the same as .055 times 100, which is 5.5.</p>
<p>Floats also have limitations—floats are accurate enough for general-purpose use, but if you need to store a number with an extremely long decimal value, you will need to look into the arbitrary precision math functions (BCMath or GMP) on the PHP Web site.</p>
<p>Also, because of these limitations, you must realize that a float isn&#8217;t always exactly what you think it is. For example, 1/3 can only be represented as .33333333… in the computer&#8217;s memory; the 3&#8217;s repeat forever, so it&#8217;s impossible to be completely accurate. It&#8217;s best to decide on how much precision you desire (for instance, if dealing with money, you&#8217;d choose 2 decimal places) and keep in mind that your decimals are no more accurate than that. Thus, you will reduce your chances for strange results when doing calculations (which is discussed in Chapter 4, &#8220;Arithmetic&#8221;).</p>
<p>Arrays<br />
Arrays are a little different than the numeric data types discussed so far. Arrays can be thought of as lists of variables, all contained within one variable. These variables can contain values of any data type, including being arrays themselves. For example, if five people are involved in a task, their names could be stored in a five-element array, with one element for each person. The people on the task, represented collectively by the array, would each have their information stored in separate variables within the array.</p>
<p>Array Indexing<br />
The names could then be retrieved using array indexing—adding a subscript (or location within the array) to the end of an array&#8217;s name to retrieve the value of that element. (An element is a single variable contained within an array.)</p>
<p>The following example demonstrates the construction of an array containing five names, then printing each name on a separate line:</p>
<pre>
<code>

&lt;?php
/* ch02ex03.php – demonstration of arrays */

$namesArray = Array('Joe', 'Bob', 'Sarah', 'Bill', 'Suzy');

echo "$namesArray[0]
";
echo "$namesArray[1]
";
echo "$namesArray[2]
";
echo "$namesArray[3]
";
echo "$namesArray[4]
";

?&gt;


</code></pre>
<p>NOTE</p>
<p>The<br />
tags are given here to separate each element of the array on a separate line.</p>
<p>It&#8217;s important to notice that the first element of an array is given by the subscript 0 and not 1. While this may seem awkward, it is fairly common in programming languages because of the way arrays are handled in memory.</p>
<p>TIP</p>
<p>Why is the first index of an array always 0? In many languages, namely C (because most of the other languages that do it are based off C), there&#8217;s a very good reason. An array would be given an area of memory when it was created, and in that area of memory, the array&#8217;s elements are stored in order. The array name only contains the address of the first element of the array. Thus, the index given would be the offset from the address; that is, the index shows how many positions to move ahead in memory.</p>
<p>So, the first element of the array would be indexed at its address plus 0, the second would be indexed at the address of the first plus 1, and so on. This behavior has made its way into most of today&#8217;s languages.</p>
<p>Arrays can be constructed as shown previously, or alternatively by assigning a value to a new element, which can either be automatically added to the end or inserted at an explicitly specified index within the array.</p>
<p>The following example demonstrates the use of empty brackets after an array to add new elements and also explicitly defines a certain element in an array:</p>
<pre>
<code>

$namesArray = Array('Joe', 'Bob', 'Sarah', 'Bill', 'Suzy');
$namesArray[] = 'Rachel'; // adds 'Rachel' as $namesArray[5]
$namesArray[3] = 'John'; // replaces 'Bill' with 'John'

</code></pre>
<p>Generally, the Array() function is used to create an array for which all values are hard-coded; the empty brackets construct is used when the array will have an unknown number of variables added to it; and the specific subscript method is used whenever a specific value needs to be accessed or changed.</p>
<p>Strings<br />
Strings are values that contain text—anything from one character to a whole string of characters (hence the name). For example, a sentence such as &#8220;This is a string&#8221; is a string value.</p>
<p>There are two types of strings: those that are single-quoted and those that are double-quoted.</p>
<p>Single-quoted strings are always interpreted just as they are. For example, to use &#8220;My variable is called $myVariable&#8221; as a string, use the statement found in the following example:</p>
<pre>
<code>

&lt;?php
/* ch02ex04.php – shows use of single-quoted strings */

echo 'My variable is called $myVariable';

?&gt;


</code></pre>
<p>The output from this example is</p>
<p>My variable is called $myVariable</p>
<p>As you may have noticed from the echo statements found earlier in this chapter, double-quoted strings are interpreted so that variables are expanded before they are actually stored as a value. Consider the following example:</p>
<pre>

<code>

&lt;?php
/* ch02ex05.php – shows use of double-quoted strings */
// Do single-quote assignment and output result
$myVariable = 'My variable is called $myVariable';
echo $myVariable;

// Move to new line
echo '
';

// Do double-quote assignment and output result
$myVariable = "My variable is called $myVariable";echo $myVariable;

?&gt;


</code></pre>
<p>The output from this example is</p>
<p>My variable is called $myVariable<br />
My variable is called My variable is called $myVariable</p>
<p>The first assignment works just as the single-quoted assignment earlier: The text is assigned just as you see it. Thus, the first line of output shows the string just as it appears in the code.</p>
<p>However, the second assignment uses a double-quoted string, so the string is interpreted before it is stored in the variable. Thus, $myVariable is expanded using its current value (that of the first assignment), and then the new value is stored in the variable, yielding the string found on the second line of output.</p>
<p>Character Escaping<br />
Some characters, such as the dollar sign, have special meaning within strings. In addition, sometimes you need to include quotes within your strings, which would typically signal the end of the string.</p>
<p>To avoid this, we use character escaping, which tells PHP to interpret a character as a literal part of the string instead of a special character (one that would signal a variable or the end of a string).</p>
<p>To escape a character, precede it with a backslash, like this:</p>
<p>\char</p>
<p>Here, char is any single character, such as a dollar sign or quote.</p>
<p>The following example uses character escaping to include $strSmall&#8217;s name and its contents surrounded by quotes inside the string $strBig:</p>
<pre>
<code>

&lt;?php
/* ch02ex06.php – demonstrates character escaping */
$strSmall = "John Smith";

$strBig = "The name stored in \$strSmall is \"$strSmall\".";
echo $strBig;

?&gt;

</code></pre>
<p>Take time to study the assignment of $strBig, as it demonstrates both the escaping of the dollar sign and of quote characters, both of which are interpreted literally as part of the string when encountered in their escaped form.</p>
<p>Thus, the output of the above program is</p>
<p>The name stored in $strSmall is &#8220;John Smith&#8221;.</p>
<p>String Indexing<br />
Strings have an indexing feature that makes them much like an array of letters. To find the letter at a given position, use the following syntax:</p>
<pre>
<code>

$string{index}

</code></pre>
<p>Here, $string should be any string variable and index should be a position within that string for which you want the letter.</p>
<pre>
<code>

For example, take a look at the following program:


&lt;?php
/* ch02ex07.php – demonstrates string indexing */

// Assign a name to $strName
$strName = "Walter Smith";

// Output the fifth letter of the name
echo $strName{4};

?&gt;

</code></pre>
<p>NOTE</p>
<p>The index for the fifth letter is actually 4 because indexing of strings, like that of arrays, begins with 0.</p>
<p>Objects<br />
Objects are a powerful method of program organization. They are essentially what people are talking about when they refer to OOP or Object-Oriented Programming. Objects (and their definitions, called classes) are discussed in depth in Chapter 12, &#8220;Using Include Files (Local and Remote).&#8221;
</p>
]]></content:encoded>
			<wfw:commentRSS>http://www.kekh.com/chapter-2/variable-types/feed/</wfw:commentRSS>
		</item>
	</channel>
</rss>
