<?xml version="1.0" encoding="UTF-8"?>
<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/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>HTML and PHP Resources</title>
	<atom:link href="http://www.htmlandphp.com/feed" rel="self" type="application/rss+xml" />
	<link>http://www.htmlandphp.com</link>
	<description>Short easy to follow tutorials &#38; more...</description>
	<lastBuildDate>Thu, 01 Mar 2012 14:56:14 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
<xhtml:meta xmlns:xhtml="http://www.w3.org/1999/xhtml" name="robots" content="noindex" />
		<item>
		<title>Introduction to custom functions in PHP</title>
		<link>http://www.htmlandphp.com/beginner-php/introduction-to-custom-functions-in-php.html</link>
		<comments>http://www.htmlandphp.com/beginner-php/introduction-to-custom-functions-in-php.html#comments</comments>
		<pubDate>Thu, 01 Mar 2012 14:55:31 +0000</pubDate>
		<dc:creator>Bladymir</dc:creator>
				<category><![CDATA[Beginner PHP]]></category>
		<category><![CDATA[Start Writing PHP]]></category>

		<guid isPermaLink="false">http://www.htmlandphp.com/?p=541</guid>
		<description><![CDATA[<p>Introduction The PHP language has a few thousand functions built in and ready to use. Although several thousand functions exist it is entirely possible that the a function to accomplish something you are looking for may be too general for your purposes &#8230; <a href="http://www.htmlandphp.com/beginner-php/introduction-to-custom-functions-in-php.html">Continue reading <span class="meta-nav">&#8594;</span></a></p><p><a href="http://www.htmlandphp.com" title="Simple easy to follow html and php video tutorials.">Visit www.HTMLandPHP.com for more information!</a></p>]]></description>
			<content:encoded><![CDATA[<h3>Introduction</h3>
<p>The PHP language has a few thousand functions built in and ready to use. Although several thousand functions exist it is entirely possible that the a function to accomplish something you are looking for may be too general for your purposes or not exist at all.</p>
<p>Although a large number of functions in PHP may take parameters and do operations on those parameters, functions are also a great way to group commonly used code in order to improve readability and maintainability of a program.</p>
<h3>Defining a Function</h3>
<p>To define a function we are required to use the keyword, <strong><em>function</em></strong> followed by the function&#8217;s name and parenthesis encasing any parameters separated by a comma and a block of code wrapped in curly brackets.</p>
<p>Function definition without parameters: </p><pre class="crayon-plain-tag"><code>function printHello(){ echo 'Hello!'; }</code></pre>
<p>Function definition with one parameter: </p><pre class="crayon-plain-tag"><code>function sayHello($name){ echo 'Hello ', $name, '!'; }</code></pre>
<h3>Function Names</h3>
<p>Functions can have just about any name as long as they begin with a letter or underscore, the first character can be followed by any letter/number/underscore combination.</p>
<p>Names that are PHP keywords or already existing functions should be avoided. Naming custom functions the same as existing functions will result in error and will keep your script from running.</p>
<p>PHP does not support function overloading or re declaring of functions. Be unique and descriptive when naming your functions.</p>
<p>(Function overloading is simply when you define multiple functions with the same name, differing only in the number of parameters. To set optional parameters in php, you can use default values when you declare your function (see next section.))</p>
<h3>Function Parameters</h3>
<p>When we declare our custom function we can define the number of parameters that our function can accept. The number of parameters can range from none to as many as you want, they only need to be separated by a comma.</p>
<pre class="crayon-plain-tag"><code>// No Parameters
function hello0(){ /*code*/ }
// One Parameter
function hello1($par1){ /*code*/ }
// Two Parameter
function hello2($par1, $par2){ /*code*/ }
// Three Parameter
function hello3($par1, $par2, $par3){ /*code*/ }</code></pre><p> The names that are given to our parameters will be the names we will use inside our function&#8217;s block of code. </p><pre class="crayon-plain-tag"><code>function showName($name) {
echo $name;
}</code></pre><p><p><p><p> In the example above, our only parameter was given the identifier of <em>$name</em> and that is what is used inside our function to use the passed parameters value.</p>
<p>It should be noted that is the parameter that was passes is changed inside the function, the original value will remain unchanged.</p>
<pre class="crayon-plain-tag"><code>function changeName($name){
$name = 'James';
}

$user = 'Joe';
changeName($user);
echo $user; // Joe - still</code></pre><p><p><p><p><p> It should be noted that php functions can have optional parameters (which addresses the issue of function overloading). We have the freedom of setting default values for our functions, these default values are used when no value is passed to our function. Consider the example below:</p>
<pre class="crayon-plain-tag"><code>function printName($name = &quot;No Name&quot;){
echo $name;
}

$user = 'Joe';
printName($user);//echo's Joe
printName(); // echo's No Name</code></pre><p><p><p><p><p><p> Note how the parameter has become optional, if we do not specify a parameter, then the default from our function declaration is used. One thing to keep in mind about optional parameters is that <strong>no required parameters must come after the optional parameters.</strong> That is, you have to make sure any optional parameters are specified after required parameters(parameters with no default specified).</p>
<h3>Passing By Reference</h3>
<p>In our previous example the value held by our $<em>user</em> variable remained unchanged, this is because the value of the parameter is copied when it is passed to a function. In order for our original variable to be accessible and changeable we need to pass it by reference. Passing by reference simply means that our identifier inside our function will refer to the exact location in memory for the value that is being passed, rather than create a copy of it to work with.</p>
<p>Since <em>$name</em> inside our function refers to the same exact place and value as $<em>user</em> any changes to <em>$name</em> will also apply to <em>$user.</em></p>
<p>To pass by reference, we simply add a ampersand(&amp;) symbol to our parameter when we declare our function.</p><pre class="crayon-plain-tag"><code>function changeName(&amp;amp;$name){
$name = 'James';
}

$user = 'Joe';
changeName($user);
echo $user; // James - name changed!</code></pre><p><p><p><p><p><p><p>
<h3>Return Values</h3>
<p>Lastly we arrive at return values. Return values are data that a function send back when it finished running, the functions we have created so far do not return data after execution. To return data we must use the <strong>return</strong> keyword, followed by the variable name or data we are trying to return. It should be noted that the <strong>return</strong> keyword marks the end of the function, no code after the <strong>return</strong> is executed (unless you wrap your return in conditionals.) Consider the example below:</p><pre class="crayon-plain-tag"><code>function getName(){
$name = 'James';
return $name;
}

$user = getName();
echo $user; // James</code></pre><p><p><p><p><p><p><p><p>
We defined a function <em>getName()</em> which returns the value <em>James. </em>When we call the function the value is returned and we store the result in the variable <em>$user,</em> just as if it had been a string. Had we not returned the value from inside the function, the data would have ceased to exist after the function reached its end. We would not have had a value for our $<em>user</em> variable.</p>
<p>Note that you can return any type of data from a function, strings, integers, arrays, ect.</p>
<h3>Summary</h3>
<p>You should not be able to define your own custom functions, here we covered mostly the syntax and topics surrounding function, but when combined with your knowledge of other html topics it is a very powerful tool. Inside your functions body, you can do anything you can outside of a function and when it comes to reusing that particular block of code inside your function all you have to do is call your function!</p>
<p>If you have any questions, comments or suggestion feel free to leave a comment or contact me at php@htmlandphp.com.</p>
<p><a href="http://www.htmlandphp.com" title="Simple easy to follow html and php video tutorials.">Visit www.HTMLandPHP.com for more information!</a></p>]]></content:encoded>
			<wfw:commentRss>http://www.htmlandphp.com/beginner-php/introduction-to-custom-functions-in-php.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Introduction to PHP Includes</title>
		<link>http://www.htmlandphp.com/beginner-php/introduction-to-php-includes.html</link>
		<comments>http://www.htmlandphp.com/beginner-php/introduction-to-php-includes.html#comments</comments>
		<pubDate>Sat, 31 Dec 2011 14:54:33 +0000</pubDate>
		<dc:creator>Bladymir</dc:creator>
				<category><![CDATA[Beginner PHP]]></category>
		<category><![CDATA[Start Writing PHP]]></category>

		<guid isPermaLink="false">http://www.htmlandphp.com/?p=521</guid>
		<description><![CDATA[<p>Introduction PHP includes refers to the four statements include, include_once, require, and require_once. These statements allow us to include PHP code written in other files in our current file and execute it as if it was part of our current one. Example Lets take &#8230; <a href="http://www.htmlandphp.com/beginner-php/introduction-to-php-includes.html">Continue reading <span class="meta-nav">&#8594;</span></a></p><p><a href="http://www.htmlandphp.com" title="Simple easy to follow html and php video tutorials.">Visit www.HTMLandPHP.com for more information!</a></p>]]></description>
			<content:encoded><![CDATA[<h3>Introduction</h3>
<p>PHP includes refers to the four statements <strong><em>include, include_once, require, </em></strong>and <strong><em>require_once.</em></strong> These statements allow us to include PHP code written in other files in our current file and execute it as if it was part of our current one.</p>
<h3>Example</h3>
<p>Lets take a simple HTML page and make it more dynamic with PHP.</p>
<p><a title="Sample HTML page" href="http://www.htmlandphp.com/examples/php/beginner/example_page.php">example_page.php</a></p><pre class="crayon-plain-tag"><code>&lt;?php
$title = &quot;Greatest Page!&quot;;
?&gt;
&lt;html&gt;
    &lt;head&gt;
        &lt;title&gt;
            &lt;?php echo $title; ?&gt; 
        &lt;/title&gt;
        &lt;style&gt;
            header {border-bottom:dotted 1px #AAA;}
            footer {border-top:dotted 1px #AAA;}
        &lt;/style&gt;
    &lt;/head&gt;
    &lt;body&gt;
        &lt;header&gt;
            &lt;h1&gt;
                &lt;?php echo $title; ?&gt;
            &lt;/h1&gt;
            &lt;p&gt;
                &lt;a href=&quot;#&quot;&gt;Home&lt;/a&gt; |
                &lt;a href=&quot;#&quot;&gt;About Us&lt;/a&gt; |
                &lt;a href=&quot;#&quot;&gt;Contact Us&lt;/a&gt;
            &lt;/p&gt;
        &lt;/header&gt;
        &lt;section&gt;
            &lt;h1&gt;Page1&lt;/h1&gt;
            &lt;p&gt;Hello World!&lt;/p&gt;
        &lt;/section&gt;
        &lt;footer&gt;
            &lt;p&gt;
                &lt;a href=&quot;#&quot;&gt;Home&lt;/a&gt; |
                &lt;a href=&quot;#&quot;&gt;About Us&lt;/a&gt; |
                &lt;a href=&quot;#&quot;&gt;Contact Us&lt;/a&gt;
            &lt;/p&gt;
        &lt;/footer&gt;
    &lt;/body&gt;
&lt;/html&gt;</code></pre></p>
<p>We can see that this page contains some reoccurring elements. We can take these reoccurring elements and put them in their own files and make it easier to reuse and maintain. For example if in the future you need to add a link to your pages you can edit a single file and the change will be reflected in all your pages, since they will all be pulling the same code from the same file.</p>
<p>Lets go ahead and split the code up into three files.</p>
<p>header.php </p><pre class="crayon-plain-tag"><code>&lt;html&gt;
    &lt;head&gt;
        &lt;title&gt;
            &lt;?php echo $title; ?&gt; 
        &lt;/title&gt;
        &lt;style&gt;
            header {border-bottom:dotted 1px #AAA;}
            footer {border-top:dotted 1px #AAA;}
        &lt;/style&gt;
    &lt;/head&gt;
    &lt;body&gt;
        &lt;header&gt;
            &lt;h1&gt;
                &lt;?php echo $title; ?&gt;
            &lt;/h1&gt;
            &lt;p&gt;
                &lt;a href=&quot;#&quot;&gt;Home&lt;/a&gt; |
                &lt;a href=&quot;#&quot;&gt;About Us&lt;/a&gt; |
                &lt;a href=&quot;#&quot;&gt;Contact Us&lt;/a&gt;
            &lt;/p&gt;
        &lt;/header&gt;</code></pre></p>
<p>home.php </p><pre class="crayon-plain-tag"><code>&lt;section&gt;
    &lt;h1&gt;Page1&lt;/h1&gt;
    &lt;p&gt;Hello World!&lt;/p&gt;
&lt;/section&gt;</code></pre></p>
<p>footer.php </p><pre class="crayon-plain-tag"><code>&lt;footer&gt;
            &lt;p&gt;
                &lt;a href=&quot;#&quot;&gt;Home&lt;/a&gt; |
                &lt;a href=&quot;#&quot;&gt;About Us&lt;/a&gt; |
                &lt;a href=&quot;#&quot;&gt;Contact Us&lt;/a&gt;
            &lt;/p&gt;
        &lt;/footer&gt;
    &lt;/body&gt;
&lt;/html&gt;</code></pre></p>
<p>Now that we have the code split up this way, we can reuse the code for our header and footer sections.</p>
<h3>Including the Content</h3>
<p>We have split the code up and now we are ready to use our methods, <strong>include, include_once, require</strong><em> and </em><strong>require_once</strong><em>. </em></p>
<p>These methods simply include the code of the specified location to our current file. for example, let create a new file, landing.php with the following code:</p>
<p><a title="Landing Example" href="http://www.htmlandphp.com/examples/php/beginner/landing.php">landing.php</a> </p><pre class="crayon-plain-tag"><code>&lt;?php
// Variable is used in our header
$title = &quot;Greatest Page!&quot;;
include 'header.php';
?&gt;

        &lt;section&gt;
            &lt;h1&gt;Welcome!&lt;/h1&gt;
            &lt;p&gt;Hola! Hello! Hallo! Salut!&lt;/p&gt;
        &lt;/section&gt;
&lt;?php
include 'footer.php';
?&gt;</code></pre></p>
<p>If you take a look at the final rendering of the page, you will notice it is the same as the original. These functions allow us to include code from other sources.</p>
<p>Its also important to note that variables can be used across included files, as long as it has been declared before the line it is used on. In our example we declared the variable $<em>title</em> and used it in our header file.</p>
<h3>Syntax</h3>
<p>These statements can be used with or with out parenthesis.</p>
<pre class="crayon-plain-tag"><code>include 'path/to/file.ext';

include('path/to/file.ext');</code></pre><p><p><p><p><p><p></p><pre class="crayon-plain-tag"><code>include_once 'path/to/file.ext';

include_once('path/to/file.ext');</code></pre><p><p><p><p><p><p><p></p><pre class="crayon-plain-tag"><code>require 'path/to/file.ext';

require('path/to/file.ext');</code></pre><p><p><p><p><p><p><p><p></p><pre class="crayon-plain-tag"><code>require_once 'path/to/file.ext'

require_once('path/to/file.ext');</code></pre><p><p><p><p><p><p><p><p>
<p>The path provided can be absolute or relative to the current directory or the include path specified in php.ini.</p>
<h3>Including vs Requiring</h3>
<p>These two constructs do the same thing and are interchangeable for the most part. The real difference is in the way that they handle errors.</p>
<p>Include issues a notice and execution of the script continues if the path of the specified file is not found.</p>
<p>Require issues an error and execution of the script stop at that point.</p>
<h3>Do it just once</h3>
<p>The two constructs <strong><em>require_once</em></strong> and <strong><em>include_once</em></strong> also do the same as <strong><em>require</em></strong> and <strong><em>include</em></strong> although as the name suggest they only do it once.What I mean by this is that if you had written two include statements in your script at different point for inclusion of the same file, the file would be included twice and the code in that file would be executed twice.</p>
<p>With the <strong><em>require_once</em></strong> and <strong><em>include_once</em></strong> constructs the PHP parser ignores any subsequent request for inclusion from <strong><em>require_once</em></strong> and <strong><em>include_once.</em></strong></p>
<p>It should be noted that any inclusion request using <strong><em>include </em></strong>and<strong> <em>require</em></strong> will be fulfilled normally. Use the constructs <strong><em>require_once</em></strong> and <em><strong>include_once</strong></em> to include any files that define functions, classes or other code that you do not want to be re-declared or executed a second time.</p>
<h3>Summary</h3>
<p>The constructs discussed here are simply a way to include contents of another file into the current one. The contents of the included files will be executed and displayed as if they had been written in the file that including it. Variables declared before the inclusion can be used in the included file, and variables, functions and classes declared inside the included file can be used in the file that including it.</p>
<p><a href="http://www.htmlandphp.com" title="Simple easy to follow html and php video tutorials.">Visit www.HTMLandPHP.com for more information!</a></p>]]></content:encoded>
			<wfw:commentRss>http://www.htmlandphp.com/beginner-php/introduction-to-php-includes.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Introduction to Loops in PHP</title>
		<link>http://www.htmlandphp.com/beginner-php/introduction-to-loops-in-php.html</link>
		<comments>http://www.htmlandphp.com/beginner-php/introduction-to-loops-in-php.html#comments</comments>
		<pubDate>Sat, 31 Dec 2011 00:00:48 +0000</pubDate>
		<dc:creator>Bladymir</dc:creator>
				<category><![CDATA[Beginner PHP]]></category>
		<category><![CDATA[Start Writing PHP]]></category>

		<guid isPermaLink="false">http://www.htmlandphp.com/?p=494</guid>
		<description><![CDATA[<p>Introduction At the heard of the matter loops are a mechanism for executing instructions (code) multiple times. Loops give us the ability to automate certain tasks that can be done in a number or repeatable steps. Types of Loops In &#8230; <a href="http://www.htmlandphp.com/beginner-php/introduction-to-loops-in-php.html">Continue reading <span class="meta-nav">&#8594;</span></a></p><p><a href="http://www.htmlandphp.com" title="Simple easy to follow html and php video tutorials.">Visit www.HTMLandPHP.com for more information!</a></p>]]></description>
			<content:encoded><![CDATA[<h3>Introduction</h3>
<p>At the heard of the matter loops are a mechanism for executing instructions (code) multiple times.</p>
<p>Loops give us the ability to automate certain tasks that can be done in a number or repeatable steps.</p>
<h3>Types of Loops</h3>
<p>In PHP we have various types of loops and although at the core of it all they do the same thing, they go about doing it differently. Its important to note that certain things can be done with less effort in some loop structures while it may not be the case for other loop structures.</p>
<h3>Notes on Loop Syntax</h3>
<p>Loop syntax varies slightly for all loops, but the important thing to keep in mind is that the loops conduct a check before every iteration and expect a Boolean value during this check. This Boolean value tells the PHP interpreter whether it should continue to the rest of the code or continue executing the current block of code contained by the loop structure.</p>
<p>Loop structures have a block of code that is executed when the Boolean value is set to true. The block of code is defined between curly brackets ( { and } ), but if the curly brakets are omitted, then only the line following the loop declaration will be considered part of the loop&#8217;s block.</p>
<h4> &#8221;<em><strong>while</strong></em>&#8221; and &#8220;<em><strong>do</strong></em>&#8220;.. &#8220;<em><strong>while</strong></em>&#8221; Loops</h4>
<p>The <strong><em>while</em></strong> loop is the simplest in terms of syntax and has the widest range of uses. Declaring a while loop is as simple as using the keyword, <strong><em>while</em></strong>, followed by a boolean value or boolean expression wrapped in parenthesis followed by a block of code in curly brackets.</p>
<p><a title="While loop example" href="http://www.htmlandphp.com/examples/php/beginner/example_while.php" rel="nofollow" target="_blank">example_while.php</a>:</p><pre class="crayon-plain-tag"><code>&lt;?php
$x = 0;

while($x &lt; 10) {
    echo $x, &quot;&lt;br&gt;\n&quot;;
    $x++;
}</code></pre></p>
<p>Take note that the expression: $x &lt; 10 , is a evaluated to a true or false, and the code between the curly brackets is executed only when this expression is true. Be aware that we can substitute any boolean expression in this place.</p>
<p style="padding-left: 30px;"><em><strong>Warning</strong>: Setting forth an infinite(∞) loop is a possibility when the expression </em><strong>never</strong><em> evaluates to </em><strong>false</strong><em>, in which case the script would run the code in the loop until either the server kills the script or the server runs out of resources. This can be a problem in a shared hosting environment, where a web host may suspend your hosting for excessive use of resources. </em></p>
<p>The <strong><em>do&#8230;while</em></strong> loop is a variation of the <strong><em>while</em></strong> loop. The <strong><em>do&#8230;while</em></strong> loop guarantees that the block of code in the loop will be executed at least once. To use this type of loop, you use the keyword, <strong><em>do</em></strong>, followed by the block of code in curly brackets and the keyword <strong><em>while</em></strong> with a Boolean value or expression in parenthesis.</p>
<p><a title="Do While loop example" href="http://www.htmlandphp.com/examples/php/beginner/example_do_while.php" rel="nofollow" target="_blank">example_do_while.php</a>:</p><pre class="crayon-plain-tag"><code>&lt;?php

$x = 0;
do{
    echo $x;
    $x++;
} while ($x &lt; 0);</code></pre></p>
<p>Its important to note in this example the comparison is between a variable and a value of zero, the expression at the end will evaluate to false and the loop will stop there. However the code block was executed once because the comparison did not take place until after the block of code. This is a property unique to the <strong><em>do&#8230;while</em></strong> loop.</p>
<p>Note: The semi-colon after the <em>while(..)</em> is required, otherwise the code will yield errors.</p>
<h4>Parts of a &#8220;<em>for</em>&#8221; loop</h4>
<p>A <em><strong>for</strong></em> loop is a bit more complex than its while counter part, it contains a variable initialization, check condition, and a step.</p>
<p>This loop can be said to be a loop that keeps track of its own progress. A typical for loop is declared by using the keyword, <strong><em>for</em></strong>, followed by the three mentioned items wrapped in parenthesis and the block of code that will be executed.</p>
<p><a title="For Loop Example" href="http://www.htmlandphp.com/examples/php/beginner/example_for.php" rel="nofollow" target="_blank">example_for.php</a>:</p><pre class="crayon-plain-tag"><code>&lt;?php
$genres = array('Blues', 'Country', 'Rock', 'Rap');

/*
 * Start our index at 0
 * 
 * Execute the block as long as the number is
 * less than the number of items in the array
 * 
 * After executing the code, add one to the count (index).
 */
for($index = 0; $index &lt; count($genres); $index++) {
    // Access the n-th element of he $genres array. 
    // n-th refers to the number held by $index.
    echo 'Do you like ', $genres[$index] ,&quot; music?&lt;br&gt;\n&quot;;
}

/*
 * Simple example 2, counting from 1 to 10
 */
for($num = 1; $num &lt;= 10; $num++){
    echo $num, ',';
}</code></pre></p>
<p>As you can see from our example, the variable <em>$num</em> is declared and set to a value of one when we declare our <strong><em>for</em></strong> loop. The second part of the parameter listing is the boolean check that dictates the number of iterations our loop will go through. The last parameter is the step that our loop is to take after executing the block of code, in this case our step adds one to the value of <em>$num</em>.</p>
<p>It should also be noted that the variable <em>$num</em> will be available outside the block of the for loop, it&#8217;s continues to exist after the loop.</p>
<h3>The &#8220;<em>foreach</em>&#8220; loop</h3>
<p>The <strong><em>foreach</em></strong> loop is a special type of loop that is best used with iterateable items like arrays and objects. A foreach loop takes uses the keyword <strong><em>foreach</em></strong> and <strong><em> as</em></strong> in the following manner.</p>
<p><a title="Foreach Example" href="http://www.htmlandphp.com/examples/php/beginner/example_foreach.php" rel="nofollow" target="_blank">example_foreach.php</a>:</p><pre class="crayon-plain-tag"><code>&lt;?php
$colors = array('red', 'blue', 'green', 'magenta','cyan','yellow');

/*
 *  Each value fo the $colors array will be referred to as
 *  a $color (singular) inside the array.
 */

foreach($colors as $color){
    echo 'Do you like the color ', $color ,&quot;?&lt;br&gt;\n&quot;;
}</code></pre></p>
<p>Note that each of the items in our array (<em>$list</em>) was referred to as <em>$a_value</em> inside the block of code.</p>
<p>The number of time the loop would execute is dependent on how many items are in the provided parameter.</p>
<p>If you have an associative array (or an object) you can also use the following syntax to retrieve the name of the key (or property) and the value.</p>
<p><a title="Foreach Example" href="http://www.htmlandphp.com/examples/php/beginner/example_foreach_key_value.php" rel="nofollow" target="_blank">example_foreach_key_value.php</a>:</p><pre class="crayon-plain-tag"><code>&lt;?php

$alphabet = array(  'first'  =&gt; 'a',
                    'second' =&gt; 'b',
                    'third'  =&gt; 'c');

foreach($alphabet as $spot =&gt; $letter) {
    /* Each key and value combo will be referred to as 
     * $spot for the key name
     * $letter for the value of each key and value combination
     */
    echo 'The ', $spot ,' letter is ', $letter, &quot;.&lt;br&gt;\n&quot;;
}</code></pre></p>
<p>Take note how the =&gt; operator was used to indicate the name of the variable we used to reference the key and the name of the variable we used to reference the value of the current element.</p>
<p>The foreach loop is commonly used to deal with arrays when each value in the array needs to  be processed.</p>
<h3>Comparison</h3>
<p>Below we have an example of how the we can print the contents of an array to the screen using all the types of loops covered above.</p>
<p><a title="Comparison Example" href="http://www.htmlandphp.com/examples/php/beginner/example_loops_comparison.php" rel="nofollow" target="_blank">example_loops_comparison.php</a>:</p><pre class="crayon-plain-tag"><code>&lt;?php
echo '&lt;pre&gt;';
$br = &quot;\n&quot;;     // Line Break

$list = array(  'Monday',
                'Tuesday',
                'Wednesday',
                'Thursday',
                'Friday',
                'Saturday',
                'Sunday'    );

/*
 *  USING WHILE LOOP
 */
echo $br, &quot;+WHILE OUTPUT------------------------------+&quot;, $br;

$count = 0;     // Array index begins at 0
while ($count &lt; count($list)) {
    echo $list[$count] ,  $br;
    $count++;   // Move index to next one by adding 1
}

/*
 *  USING A DO WHILE LOOP
 */
echo $br, &quot;+DO...WHILE OUTPUT------------------------------+&quot;, $br;

$count = 0;   // Reset our count
do {
    echo $list[$count] ,  $br;
    $count++;   // Move index to next one by adding 1
} while ($count &lt; count($list));

/*
 *  USE A FOR LOOP
 */
echo $br, &quot;+FOR OUTPUT------------------------------+&quot;, $br;

for ($count = 0; $count &lt; count($list); $count++) {
    echo $list[$count] ,  $br;
}

/*
 *  USE A FOREACH LOOP
 */
echo $br, &quot;+FOREACH OUTPUT------------------------------+&quot;, $br;

foreach ($list as $day) {
    echo $day,  $br;
}


echo $br, &quot;print_r OUTPUT------------------------------+&quot;, $br;

print_r($list);
echo '&lt;/pre&gt;';</code></pre></p>
<h3>Breaking out</h3>
<p>Loops check whether a condition has changed after every iteration, sometimes its necessary to exit a loop when a condition outside this primary condition is reached. The <strong><em>break</em></strong> keyword is used inside a loop to indicate that the loop should be exited.</p>
<p><a title="Comparison Example" href="http://www.htmlandphp.com/examples/php/beginner/example_loops_break.php" rel="nofollow" target="_blank">example_loops_break.php</a>:</p><pre class="crayon-plain-tag"><code>&lt;?php
$br = &quot;&lt;br&gt;\n&quot;;
// Numbers from 0 to 4 displayed
$count = 0;     
while ($count &lt; 5) {
    echo $count, $br;
    $count++;   
}


// Numbers 0 displayed
$count = 0;
while ($count &lt; 5) {
    echo $count, $br;
    $count++;   

    // Exit our loop
    break;
}

// Numbers from 0 to 3
$count = 0;
while ($count &lt; 5) {
    echo $count, $br;
    $count++;   

    // Exit our loop when count reaches a value of 4
    if($count == 4)
        break;
}</code></pre></p>
<p>In the example above we have a break statement inside our while loop that simply exits the loop as soon as the PHP parser reaches the line. We also have the break after an if-condition that allows us to specify when we should exit the loop.</p>
<p>Using the break keyword is simple, and it is typically used to exit loops in special cases specified by you with series of conditionals inside the loop. The example demonstrated this ability with the while loop, but it works in the same manner with the other types of loops.</p>
<h3>Summary</h3>
<p>In summary the loop structures in PHP are, <strong><em>while, do&#8230;while, for, </em></strong>and <strong><em>foreach</em></strong>. These loops have varying syntax&#8217;s and required parameters. At the root they all execute a block of code a number of times dictated by a given condition.  Note that they can be used interchangeably for the most part, but certain tasks are made easier by some loop structures.</p>
<p><a href="http://www.htmlandphp.com" title="Simple easy to follow html and php video tutorials.">Visit www.HTMLandPHP.com for more information!</a></p>]]></content:encoded>
			<wfw:commentRss>http://www.htmlandphp.com/beginner-php/introduction-to-loops-in-php.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>PHP Functions that Help You Debug</title>
		<link>http://www.htmlandphp.com/beginner-php/php-functions-that-help-you-debug.html</link>
		<comments>http://www.htmlandphp.com/beginner-php/php-functions-that-help-you-debug.html#comments</comments>
		<pubDate>Sat, 24 Dec 2011 03:29:30 +0000</pubDate>
		<dc:creator>Bladymir</dc:creator>
				<category><![CDATA[Beginner PHP]]></category>
		<category><![CDATA[Other Beginner PHP]]></category>

		<guid isPermaLink="false">http://www.htmlandphp.com/?p=470</guid>
		<description><![CDATA[<p>Introduction Writing code can be a daunting task filled with unexpected twist and turns even when we feel that we have everything planned out. We will be covering some of the major functions in PHP that can be used for debugging our &#8230; <a href="http://www.htmlandphp.com/beginner-php/php-functions-that-help-you-debug.html">Continue reading <span class="meta-nav">&#8594;</span></a></p><p><a href="http://www.htmlandphp.com" title="Simple easy to follow html and php video tutorials.">Visit www.HTMLandPHP.com for more information!</a></p>]]></description>
			<content:encoded><![CDATA[<h3>Introduction</h3>
<p>Writing code can be a daunting task filled with unexpected twist and turns even when we feel that we have everything planned out.</p>
<p>We will be covering some of the major functions in PHP that can be used for debugging our code, to track down unexpected execution and unexpected errors.  The functions we will focus on are:</p>
<ul>
<li><em><strong>echo()</strong></em></li>
<li><em><strong>print_r()</strong></em></li>
<li><em><strong>var_dump()</strong></em></li>
<li><em><strong>isset() </strong></em></li>
<li><em><strong>empty()</strong></em></li>
<li><em><strong>exit()</strong></em> and <em><strong>die()</strong></em></li>
</ul>
<h3>Printing Details to the Screen</h3>
<p>PHP programming at its root is writing a set of instructions that are going to be parsed and executed. Although we may think that we know what is going to happen, we get unexpected results at times. To track down whats going wrong and where its going wrong we need to print extra statements to the screen so we can confirm that what we expect is happening is in actuality taking place.</p>
<h3>Our old friend <em>echo()</em></h3>
<p>In a script that is giving us unexpected output, it is crucial that we trace our way through the script or through what we believe to be culprit, echo provides a basic means of doing so.</p>
<p>Using extra echoes into our scripts can help us confirm the existence of a variable and the value it holds.</p>
<p>For example, below we have taken a snippet of code and we have added echo statements at different points along the script with additional information for us comments. This helps us follow the logic of the script and the value of our selected variable at different points in the execution.</p>
<p><a title="PHP Echo Dubugging Example" href="http://www.htmlandphp.com/examples/php/beginner/example_debug_echo.php" rel="nofollow" target="_blank">example_debug_echo.php</a> :</p><pre class="crayon-plain-tag"><code>&lt;?php
$number = 1;

echo '&lt;b&gt;Starting:&lt;/b&gt; '. $number .'&lt;br&gt;';  // Display our starting number
for($count = 2; $count &lt;= 10; $count += 2)
{
    echo 'Before:'. $number . '&lt;br&gt;';       // Display number before operation
    $number *= $count;
    echo 'After:'. $number . '&lt;br&gt;&lt;br&gt;';    // Display number after operation
}
echo '&lt;b&gt;Ending:&lt;/b&gt; '. $number;            // Display our final number</code></pre></p>
<p>This is an exaggerated example, but in reality we may have to do something like this in our scripts in order to track down where an error has occurred. Although this is a basic approach to debugging it can be an effective one.</p>
<h3>Printing Arrays, Object and Additional Information Printing</h3>
<p>The functions <em><strong>var_dump()</strong></em> and <em><strong>print_r()</strong></em> are used exclusively for debugging purposes. These two functions are identical in function but differ in the output that they display.</p>
<p>The <strong><em>print_r()</em></strong> function displays a variables contents in a readable format. This does not mean much for variables holding primitive data type like strings, integers and floating points, as they are simply printed to the screen, but arrays and objects get formatted into a string representation before they are printed to the screen.</p>
<p>The function <em><strong>var_dump()</strong></em> formats the value of its parameters into a readable form and displays information about the variables data type in addition to its value.</p>
<p>Here&#8217;s and example to show how both functions display the variables information in a more readable format in the case of strings and arrays.</p>
<p><a title="PHP Print_r Var_dump Dubugging Example" href="http://www.htmlandphp.com/examples/php/beginner/example_print_r_var_dump.php" rel="nofollow" target="_blank">example_print_r_var_dump.php</a> :</p><pre class="crayon-plain-tag"><code>&lt;pre&gt;
&lt;?php
$aString = &quot;Hello Dolly&quot;;
$anArray = array('name' =&gt; 'Joel', 'age' =&gt; '20');

// A String
echo &quot;A string and print_r():\n&quot;;
print_r($aString);

echo &quot;\n\nA string and var_dump():\n&quot;;
var_dump($aString);

// An Array
echo &quot;\n\nAn array and print_r():\n&quot;;
print_r($anArray);

echo &quot;\n\nAn array and var_dump():\n&quot;;
var_dump($anArray);

?&gt;
&lt;/pre&gt;</code></pre></p>
<p>Note that these functions are most useful when trying to debug arrays and objects. The visual structuring of the data makes it easier to read which arrays or properties are encased and by what names or keys they can be accessed. The <em><strong>var_dump()</strong></em> function is useful when confirming the type of data a variable holds, note in the example above, the &#8216;<em>age</em>&#8216; key of the &#8216;<em>anArray&#8217;</em> variable holds a <strong>string</strong> of value 20, rather than an <strong>integer</strong> of value 20.</p>
<h3>Is the Variable Ready</h3>
<p>Next we have the functions <strong><em>isset()</em></strong> and <strong><em>empty()</em></strong>. These function simply establish whether a variable has been set or contains a value.</p>
<p>If you recall PHP is a loosely typed language and variables are allowed to contain any type of data. Variables do not need to be declared or instantiated before they are used, but in certain cases it is useful to know if a variable has been set or if it contains any value at all.</p>
<p>The <strong>isset()</strong> function tells us if a variable has been set by returning a <strong>boolean</strong> value of <strong>true</strong> or <strong>false</strong>.</p>
<p>In the following example we can see how we can check a variable to for whether or not it has been set.</p>
<p><a title="PHP isset example" href="http://www.htmlandphp.com/examples/php/beginner/example_isset.php" target="_blank">example_isset.php</a> :</p><pre class="crayon-plain-tag"><code>&lt;?php

/*
 * Set the variable
 * Then use isset to see if we have declared it
 */
$var1 = 'Some Value';

if(isset($var1))
    echo 'Variable 1 is set! &lt;br&gt;';
else
    echo 'Variable 1 is not set!&lt;br&gt;';

/* 
 * We have not declared $var2 anywhere
 * Can you guess what the output will be?
 */
if(isset($var2))
    echo 'Variable 2 is set! &lt;br&gt;';
else
    echo 'Variable 2 is &lt;b&gt;not&lt;/b&gt; set!&lt;br&gt;';</code></pre></p>
<p>The <strong>empty()</strong> function tells us if a variable is empty,</p>
<p>In this modified example we can see that a set variables is considered empty if it contains the boolean equivalent of false or if the variable has not been set.</p>
<p><a title="Empty PHP Example" href="http://www.htmlandphp.com/examples/php/beginner/example_empty.php" target="_blank">example_empty.php</a> :</p><pre class="crayon-plain-tag"><code>&lt;?php

/*
 * set the variable and a value
 * Then use empty to see if we have an empty value
 */
$var1 = 'Some Value';

if(empty($var1))
    echo 'Variable 1 is empty! &lt;br&gt;';
else
    echo 'Variable 1 is not empty!&lt;br&gt;';

// Change the value to an empty string
$var1 = '';
if(empty($var1))
    echo 'Variable 1 is empty!(Contains an empty string) &lt;br&gt;';
else
    echo 'Variable 1 is not empty!&lt;br&gt;';

/* 
 * We have not declared $var2 anywhere
 * Can you guess what the output will be?
 */
if(empty($var2))
    echo 'Variable 2 is empty! &lt;br&gt;';
else
    echo 'Variable 2 is &lt;b&gt;not&lt;/b&gt; empty!&lt;br&gt;';</code></pre></p>
<h3>Run it or Exit() or Die()</h3>
<p>Lastly we have the constructs <strong><em>exit()</em></strong> and <strong><em>die()</em></strong>. These constructs terminate the script at the point they are used.</p>
<p>When using these constructs we can pass a string parameter that will be printed when the script exits.</p>
<p><a title="Exit and Die Example PHP" href="http://www.htmlandphp.com/examples/php/beginner/example_exit_die.php" target="_blank">example_exit_die.php</a> :</p><pre class="crayon-plain-tag"><code>&lt;?php
$error = true;

if($error)
    exit('An Error Occured. Unable to continue.'); // die() is equivalent

echo 'Welcome!';</code></pre></p>
<p>Note that the last echo was not executed since the exit command was executed.</p>
<p>We can also use the <em><strong>or</strong></em> keyword as part of a statement with exit() and die() to determine if the script should continue. The left hand side of the <strong><em>or</em></strong> is interpreted as a boolean value, when the left hand side of the expression is false the right hand side gets executed.</p>
<p><a title="OR Exit and Die Example PHP" href="http://www.htmlandphp.com/examples/php/beginner/example_or_exit_die.php" target="_blank">example_or_exit_die.php</a> :</p><pre class="crayon-plain-tag"><code>&lt;?php
$bar = &quot;Hello&quot;;
$foo = isset($bar) or die('An Error Occured. $bar was not set.');
echo 'Welcome! $bar was set.';

/* Note we have not declared $tag*/
$fee = isset($tag) or die('An Error Occured. $tag was not set.');
echo 'Welcome! $tag was set.';</code></pre></p>
<p>The example above checks whether a variable is set and the proceeds or exits the script. It is a short hand version of the if statement in the previous example.</p>
<p>The exit and die statements can be used when debugging a script and we want to stop execution at a certain point. Note that they are interchangeable.</p>
<h3>Summary</h3>
<p>Tracking down unexpected outcomes in our scripts simplifies to finding where were we have defined incorrect logic or an incorrect order of steps. Printing the type and value of variables is helpful in order to correct any errors in our script.</p>
<ul>
<li>Printing useful information at different steps in your script with <strong><em>echo.</em></strong></li>
<li>Confirm the key and value pairs in arrays and properties of object by using the <em><strong>print_r</strong></em> and <em><strong>var_dump</strong></em> functions.</li>
<li>Check whether a variable has been instantiated by using <em><strong>isset</strong></em>.</li>
<li>See if a variable contains an empty value or has not been set by using <em><strong>empty</strong></em>.</li>
<li>Its important to note that <em><strong>isset</strong></em> is not the same as <em><strong>empty</strong></em></li>
<li>Stop execution of a script when arriving at a certain condition by using <em><strong>exit</strong></em> and <em><strong>die</strong></em>.</li>
</ul>
<p>These functions are key to debugging or narrowing down problems in PHP scripts, although they can also become part of your script in order to handle errors appropriately.</p>
<h3>Comments, Questions or Concerns</h3>
<p>If you have any comments, questions or concerns feel free to voice them on this site or contact us directly at <strong>php@htmlandphp.com</strong></p>
<p><a href="http://www.htmlandphp.com" title="Simple easy to follow html and php video tutorials.">Visit www.HTMLandPHP.com for more information!</a></p>]]></content:encoded>
			<wfw:commentRss>http://www.htmlandphp.com/beginner-php/php-functions-that-help-you-debug.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>207: Introduction to arrays in PHP</title>
		<link>http://www.htmlandphp.com/beginner-php/207-introduction-to-arrays-in-php.html</link>
		<comments>http://www.htmlandphp.com/beginner-php/207-introduction-to-arrays-in-php.html#comments</comments>
		<pubDate>Wed, 21 Dec 2011 15:45:36 +0000</pubDate>
		<dc:creator>Bladymir</dc:creator>
				<category><![CDATA[Beginner PHP]]></category>
		<category><![CDATA[Start Writing PHP]]></category>

		<guid isPermaLink="false">http://www.htmlandphp.com/?p=440</guid>
		<description><![CDATA[<p>Introduction Arrays are a special data type in PHP that is used to hold a list of data. The ability to hold a list of data is valuable as it allows us to hold and pass sets of related data to &#8230; <a href="http://www.htmlandphp.com/beginner-php/207-introduction-to-arrays-in-php.html">Continue reading <span class="meta-nav">&#8594;</span></a></p><p><a href="http://www.htmlandphp.com" title="Simple easy to follow html and php video tutorials.">Visit www.HTMLandPHP.com for more information!</a></p>]]></description>
			<content:encoded><![CDATA[<h3>Introduction</h3>
<p>Arrays are a special data type in PHP that is used to hold a list of data. The ability to hold a list of data is valuable as it allows us to hold and pass sets of related data to different point in our application with ease.</p>
<h3>Array Syntax</h3>
<p>The simplest way to use arrays is it declare one using the <strong><em>array()</em></strong> function when declaring a variable.  There are a couple different ways to add data to an array, we can assign a value to the array with an empty index or by passing the values as parameters to the <strong><em>array()</em></strong> function.</p>
<p>When the <strong><em>array()</em></strong> function is used without any parameters an empty array is created.</p><pre class="crayon-plain-tag"><code>$ourList = array();</code></pre>
<p>Passing values as parameters creates a non empty array. Passing a value to the array with an empty index also pushes a value to the end of the array.</p>
<pre class="crayon-plain-tag"><code>&lt;?php
/* Fill an array by passing values as parameters */
$ourList = array('Hello', 'World'); // pass values as parameters

var_dump($ourList);     // Visual Representation of the array.


/* Filling an array by passing an empty index */
$ourList2 = array();         // empty array
$ourList2[] = 'Hello';       // pushes a value into the array
$ourList2[] = 'World';       // pushes a value into the array

var_dump($ourList2);     // Visual Representation of the array.</code></pre></p>
<p><em><strong>Note</strong></em>: In the case that the array has not been explicitly created, simply using array syntax and assigning it a value will create an array with the key(<em>if any</em>) and values provided.</p>
<h3>Array Indices</h3>
<p>Arrays hold data as list and  list held by the array needs to be access in order to be useful. If you use a function like <em><strong>var_dump()</strong></em> or <em><strong>print_r()</strong></em> you can see a visual representation of the array like below:</p>
<table>
<tbody>
<tr>
<td>array(2) {</td>
</tr>
<tr>
<td></td>
<td>[0]=&gt;</td>
</tr>
<tr>
<td></td>
<td>string(5) &#8220;Hello&#8221;</td>
</tr>
<tr>
<td></td>
<td>[1]=&gt;</td>
</tr>
<tr>
<td></td>
<td>string(5) &#8220;World&#8221;</td>
</tr>
<tr>
<td></td>
<td>}</td>
</tr>
</tbody>
</table>
<p>Our array consists of two string values with a length of five characters. The important thing to notice is the value in the square brackets, this is the <strong><em>index</em></strong> that is used to refer to that value.</p>
<p>To access a given item in an array we simply use the name of the variable that holds the array and then use the index of the item in square brackets.</p><pre class="crayon-plain-tag"><code>&lt;?php
# Fill an array by passing values as parameters 
$names = array('Leon', 'Ivan', 'John', 'Mohamed', 'Jose'); 

echo $names[0], &quot;&lt;br&gt;\n&quot;; // Displays: Leon
echo $names[1], &quot;&lt;br&gt;\n&quot;; // Displays: Ivan
echo $names[2], &quot;&lt;br&gt;\n&quot;; // Displays: John
echo $names[3], &quot;&lt;br&gt;\n&quot;; // Displays: Mohamed
echo $names[4], &quot;&lt;br&gt;\n&quot;; // Displays: Jose

# Visual representation of array.
var_dump($names);</code></pre></p>
<p>By default array indices begin at zero and count to one minus the number of elements. So the array above has five elements and the indices range from zero to four.</p>
<p><em><strong>Note</strong></em>: Indices can also be referred to as <em><strong>key</strong></em>s.</p>
<h3>Specifying Indices(keys)</h3>
<p>PHP automatically specifies the indices for arrays when none is specified. We can specify a different key starting point or do away with numerical numbering and use a string key names for our arrays indices.</p>
<p>To start numbering at a different value, we simply use the  <em><strong>&#8220;=&gt;&#8221;</strong></em> operator when we specify our values. It should be noted that the parser will number any indices after that point in sequential order until a different index value is specified.</p><pre class="crayon-plain-tag"><code>&lt;?php
$br = &quot;&lt;br&gt;\n&quot;; // Used for formatting

/**************************  EXAMPLE 1 ************************************/
// Specify the count to start at 1 rather than 0
$ourList = array(1 =&gt; 'Mercury', 'Venus');
echo $ourList[1], $br;     // Displays: Mercury
echo $ourList[2], $br;     // Displays: Venus


/**************************  EXAMPLE 2 ************************************/
// Specify the a different index for certain values
$ourList2 = array(1 =&gt; 'Mercury', 'Venus', 4 =&gt; 'Mars');    // 3 not defined!
echo $ourList2[1], $br;     // Displays: Mercury
echo $ourList2[2], $br;     // Displays: Venus
echo $ourList2[4], $br;     // Displays: Mars


/**************************  EXAMPLE 3 ************************************/
// Specify a string key
$ourList3 = array('home' =&gt; 'Earth',        // key: home     value: Earth
                  'largest' =&gt; 'Jupiter',   // key: largest  value: Jupiter
                  'center' =&gt; 'Sun',        // key: center   value: Sun
                  'Astroid Belt');          // key: 0        value: Astroid Belt

echo $ourList3['home'], $br;        // Displays: Earth
echo $ourList3['largest'], $br;     // Displays: Jupiter
echo $ourList3['center'], $br;      // Displays: Sun
echo $ourList3[0], $br;             // Displays: Astroid Belt</code></pre></p>
<p><em><strong>Note</strong></em>: PHP does not take white space into account when parsing code, for readability the example shows how we can set different keys and values on their own line. Arrays that contains string key names are refereed to as <em><strong>associative arrays</strong></em></p>
<h3>Arrays Inside Arrays</h3>
<p>Arrays are nothing more than a list that holds other data types. Arrays can also be multi-dimensional, meaning that they can hold other arrays and those arrays can hold other arrays so on so forth. We can define arrays like the example below, or you can nest <em><strong>array()</strong></em> functions in one another.</p>
<pre class="crayon-plain-tag"><code>&lt;?php
$family = array();

// key 'adults' contains an array with keys and values
$family['adults'] = array(
                        'mother' =&gt; 'Lea', 
                        'father' =&gt; 'Lucas'
                    );

$family['children'] = array(
                        'son' =&gt; 'Leo',
                        'daughter' =&gt; 'Lisa'
                    );

echo $family['adults']['father'], &quot;&lt;br&gt;\n&quot;;      // Displays: Lea
echo $family['adults']['mother'], &quot;&lt;br&gt;\n&quot;;      // Displays: Lucas
echo $family['children']['son'], &quot;&lt;br&gt;\n&quot;;       // Displays: Leo
echo $family['children']['daughter'], &quot;&lt;br&gt;\n&quot;;  // Displays: Lisa

print_r($family);   // Visual Representation of the array</code></pre></p>
<p><em><strong>Note:</strong></em> To access the data inside the inner array you specify a key of the array holding the inner array, then the key of the enclosed array.</p>
<pre class="crayon-plain-tag"><code>$variableName['outer array key']['inner array key'];</code></pre><p><em><strong>Note:</strong></em> This pattern continues if more arrays are enclosed.</p>
<h3>Array Related Error</h3>
<p>While using arrays we may occasionally come across the following error.</p>
<pre class="crayon-plain-tag"><code>Notice: Undefined offset: key in file.php on line 20</code></pre>
<p>Depending on the PHP setting on the server, this may or may not display. In this example this is a PHP notice, which means the rest of our script will finish parsing and continue to be executed, in contrast if this was a fatal error our PHP script would stop executing all together.</p>
<p>All this notice means is we have not defined this particular key for our array. To fix this we need to specify the key the parser is trying to find at(<em>or around</em>) the line it specifies or remove this reference all together, depending on what our script is supposed to be doing.</p>
<h3>Summary</h3>
<p>Arrays are a special data type in PHP that can hold a list of data including other arrays.  Arrays have sequential numerical keys (indices), but you have the ability to specify string key names or an alternate starting number. Arrays are commonly used to group related data in order to make it simple to pass the data to different parts of an application.</p>
<h3>Comments, Questions or Concerns</h3>
<p>If you have any comments, questions or concerns feel free to voice them on this site or contact us directly at <strong>php@htmlandphp.com</strong></p>
<p><a href="http://www.htmlandphp.com" title="Simple easy to follow html and php video tutorials.">Visit www.HTMLandPHP.com for more information!</a></p>]]></content:encoded>
			<wfw:commentRss>http://www.htmlandphp.com/beginner-php/207-introduction-to-arrays-in-php.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>206: Introduction to Switch Conditionals in PHP</title>
		<link>http://www.htmlandphp.com/beginner-php/introduction-to-switch-conditionals-in-php.html</link>
		<comments>http://www.htmlandphp.com/beginner-php/introduction-to-switch-conditionals-in-php.html#comments</comments>
		<pubDate>Tue, 20 Dec 2011 06:24:43 +0000</pubDate>
		<dc:creator>Bladymir</dc:creator>
				<category><![CDATA[Beginner PHP]]></category>
		<category><![CDATA[Start Writing PHP]]></category>

		<guid isPermaLink="false">http://www.htmlandphp.com/?p=356</guid>
		<description><![CDATA[<p>Introduction Switch is another language construct that is used to control program flow. The switch construct takes a single parameter and compares it for equality to a set of cases that have been specified. Example Scenerio Let&#8217;s take an take the classic &#8230; <a href="http://www.htmlandphp.com/beginner-php/introduction-to-switch-conditionals-in-php.html">Continue reading <span class="meta-nav">&#8594;</span></a></p><p><a href="http://www.htmlandphp.com" title="Simple easy to follow html and php video tutorials.">Visit www.HTMLandPHP.com for more information!</a></p>]]></description>
			<content:encoded><![CDATA[<h3>Introduction</h3>
<p><strong><em>Switch</em></strong> is another language construct that is used to control program flow. The <strong><em>switch</em></strong> construct takes a single parameter and compares it for equality to a set of <em>cases</em> that have been specified.</p>
<h3>Example Scenerio</h3>
<p>Let&#8217;s take an take the classic case where we have seven days, represented by the numbers from zero to six.</p>
<p>We are going to pass a variable holding a number to our switch, the switch then looks for the case where the parameter it is passed is equal to a case. The parser then executes the code after the matching case. The parser continues to execute code until the end of the switch or a break statement is reached.</p>
<h3>What is a &#8220;break&#8221;?</h3>
<p>The<strong></strong><em><strong> break</strong></em> is used to tell the parser to break or stop executing the current block of code. A break statement is required to indicate the end of a block inside a switch, much like the curly brackets are used to indicate the start and end of a block after an if statement.</p>
<h3>Implementing a Switch</h3>
<h4>One Input to One Block</h4>
<p>The script below echoes the name of a day depending on the value of our variable <strong>$day.</strong> In this scenario, there is one output for a single input. </p><pre class="crayon-plain-tag"><code>&lt;?php
$day = 4;

switch ($day){
    case 0 : 
        echo 'Sunday';
        break;
    case 1 : 
        echo 'Monday';
        break;
    case 2 : 
        echo 'Tuesday';
        break;
    case 3 : 
        echo 'Wednesday';
        break;
    case 4 : 
        echo 'Thursday';
        break;
    case 5 : 
        echo 'Friday';
        break;
    case 6 : 
        echo 'Saturday';
        break;
}
?&gt;</code></pre></p>
<h4>Multiple Input to a Single Block</h4>
<p>Inside a switch we are also able to have multiple possible input values with a single output. To do this you simply group a number of cases one after another and follow with an appropriate block of code. For example the script below tells you if the number is even or odd. </p><pre class="crayon-plain-tag"><code>&lt;?php
$day = 4;

switch ($day){
    case 0 :
    case 2 :
    case 4 :
    case 6 :
    case 8 :
    case 10 :
        echo 'Even!';
        break;
    case 1 :
    case 3 :
    case 5 :
    case 6 :
    case 7 :
    case 11 :
        echo 'Odd!';
        break;
}
?&gt;</code></pre></p>
<h4>The Undefined Case</h4>
<p>If for any reason the value of the variable being compared did not have a case defined, no code inside the switch would execute since a case for that particular value is not defined. We have the option to define a default case that will be executed if the value of parameter being compared is not found. We define the default case with the <strong><em>default</em></strong> keyword in place of the case and the value.</p>
<p>In the example below we have grouped the values from zero to six so that they execute the code echoing, &#8220;Its a valid day from 0 to 6!&#8221;. If the parameter passed to the switch has any other value it will display the code defined after the default case.</p><pre class="crayon-plain-tag"><code>&lt;?php
$day = 10;

switch ($day) {
    case 0 :
    case 1 :
    case 2 :
    case 3 :
    case 4 :
    case 5 :
    case 6 :
        echo 'Its a valid day from 0 to 6!';
        break;
    default :
        echo 'Not a valid number for a day!';
        break;
}
?&gt;</code></pre></p>
<h3>Note about the &#8220;break&#8221;</h3>
<p>The break tells the parser to stop executing the current block of code. If you happen to omit the break from your cases inside the switch, the parser will execute all of the code starting at the matching case. Leaving the break out can result in unexpected output, remember to use the break to indicate the end of a cases&#8217; block of code.</p>
<h3> Switch vs If-Else</h3>
<p>You may have noticed some similarities between the switch and if-else blocks. Both of these constructs act in a similar manner and they can both <em>almost</em> be used interchangeably. The decision on which to use is yours.</p>
<h3>Comments, Questions or Concerns</h3>
<p>If you have any comments, questions or concerns feel free to voice them on this site or contact us directly at <strong>php@htmlandphp.com</strong></p>
<p><a href="http://www.htmlandphp.com" title="Simple easy to follow html and php video tutorials.">Visit www.HTMLandPHP.com for more information!</a></p>]]></content:encoded>
			<wfw:commentRss>http://www.htmlandphp.com/beginner-php/introduction-to-switch-conditionals-in-php.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Crayon Syntax Highlighter</title>
		<link>http://www.htmlandphp.com/scripts/crayon-syntax-highlighter.html</link>
		<comments>http://www.htmlandphp.com/scripts/crayon-syntax-highlighter.html#comments</comments>
		<pubDate>Mon, 19 Dec 2011 15:24:49 +0000</pubDate>
		<dc:creator>Bladymir</dc:creator>
				<category><![CDATA[Scripts]]></category>

		<guid isPermaLink="false">http://www.htmlandphp.com/?p=387</guid>
		<description><![CDATA[<p>About the Plugin Crayon Syntax Highlighter is a a fantastic plugin for WordPress created by Aram Kocharyan. The plugin enables you to post code in your WordPress posts and pages in a very easy to use way. If you are &#8230; <a href="http://www.htmlandphp.com/scripts/crayon-syntax-highlighter.html">Continue reading <span class="meta-nav">&#8594;</span></a></p><p><a href="http://www.htmlandphp.com" title="Simple easy to follow html and php video tutorials.">Visit www.HTMLandPHP.com for more information!</a></p>]]></description>
			<content:encoded><![CDATA[<h3>About the Plugin</h3>
<p>Crayon Syntax Highlighter is a a fantastic plugin for WordPress created by Aram Kocharyan. The plugin enables you to post code in your WordPress posts and pages in a very easy to use way. If you are using WordPress and plan on posting code on your site, you need to get Crayon Syntax Highlighter.</p>
<p>It is simply one of the best syntax highlighter we have come across, as you may have noticed, we use it in almost all of our post here at <a title="HTML and PHP Resource" href="http://www.htmlandphp.com">HTMLandPHP.com</a></p>
<h3>Plugin Example</h3>
<pre class="crayon-plain-tag"><code>&lt;?php
$var1 = 100;
$var2 = &quot;abc&quot;;

// Using AND
var_dump($var1 == 100 AND $var2 == &quot;abc&quot;); // True
var_dump($var1 == 200 AND $var2 == &quot;abc&quot;); // False

// Using OR
var_dump($var1 == 100 OR $var2 == &quot;abc&quot;); // True
var_dump($var1 == 200 OR $var2 == &quot;abc&quot;); // True

// Using AND and OR
var_dump(($var1 == 100 OR $var2 == &quot;def&quot;) AND ($var1 == 200 OR $var2 == &quot;abc&quot;)); // True
var_dump(($var1 == 100 AND $var2 == &quot;abc&quot;) OR ($var1 == 200 AND $var2 == &quot;abc&quot;)); // True</code></pre></p>
<p>In order to post code all we simply use the short tag and a relative path to the script and the plugin takes care of the rest.</p>
<pre class="crayon-plain-tag"><code>[crayon url=&quot;examples/php/beginner/example_and_or.php&quot;/]$</code></pre>
<p>You can also have code written right inside your post. Visit the plugins website for more details on usage and download information!</p>
<h3>Plugin Homepage</h3>
<p>Official webpage at: <a href="http://ak.net84.net/projects/crayon-syntax-highlighter/">http://ak.net84.net/projects/crayon-syntax-highlighter/</a></p>
<p>WordPress Plugin Page: <a href="http://wordpress.org/extend/plugins/crayon-syntax-highlighter/" rel="nofollow">http://wordpress.org/extend/plugins/crayon-syntax-highlighter/</a></p>
<p><a href="http://www.htmlandphp.com" title="Simple easy to follow html and php video tutorials.">Visit www.HTMLandPHP.com for more information!</a></p>]]></content:encoded>
			<wfw:commentRss>http://www.htmlandphp.com/scripts/crayon-syntax-highlighter.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Simple PHP Flat File Shoutbox</title>
		<link>http://www.htmlandphp.com/scripts/simple-php-flat-file-shoutbox.html</link>
		<comments>http://www.htmlandphp.com/scripts/simple-php-flat-file-shoutbox.html#comments</comments>
		<pubDate>Mon, 19 Dec 2011 06:10:32 +0000</pubDate>
		<dc:creator>Bladymir</dc:creator>
				<category><![CDATA[Scripts]]></category>

		<guid isPermaLink="false">http://www.htmlandphp.com/?p=363</guid>
		<description><![CDATA[<p>About The Script This is a simple PHP Shout Box or Guest Book script. All the information gathered by the script is stored in a text file as comma separated values. Further Explanation /index.php Scripts main File, It is used &#8230; <a href="http://www.htmlandphp.com/scripts/simple-php-flat-file-shoutbox.html">Continue reading <span class="meta-nav">&#8594;</span></a></p><p><a href="http://www.htmlandphp.com" title="Simple easy to follow html and php video tutorials.">Visit www.HTMLandPHP.com for more information!</a></p>]]></description>
			<content:encoded><![CDATA[<h3>About The Script</h3>
<p>This is a simple PHP Shout Box or Guest Book script. All the information gathered by the script is stored in a text file as comma separated values.</p>
<div class="attachments"><h3>Download the Script Files Now</h3><dl class="attachments attachments-large"><dt class="icon"><a title="Flat File Shout Box Script" href="http://www.htmlandphp.com/scripts/simple-php-flat-file-shoutbox.html?aid=558&amp;sa=0" rel="nofollow"><img src="http://www.htmlandphp.com/wp-content/plugins/eg-attachments/img/flags/zip.png" width="48" height="48" alt="Simple PHP Shout Box script. Includes all HTML, CSS, and PHP files." /></a></dt><dd class="caption"><strong>Title</strong> : <a title="Flat File Shout Box Script" href="http://www.htmlandphp.com/scripts/simple-php-flat-file-shoutbox.html?aid=558&amp;sa=0" rel="nofollow">Flat File Shout Box Script</a><br /><strong>Caption</strong> : Flat File Shout Box Script<br /><strong>File name</strong> : com.htmlandphp.shoutbox.1.0.1.zip<br /><strong>Size</strong> : 3 kB</dd></dl></div>
<h3>Further Explanation</h3>
<h4>/index.php</h4>
<p>Scripts main File, It is used to display the posted messages and display the form used to post messages.</p><pre class="crayon-plain-tag"><code>&lt;?php
/* Configuration */
$dataFile = './data/data.csv';

/* Required Files */
require_once './process/write.php';
require_once './process/read.php';
?&gt;
&lt;!DOCTYPE html&gt;
&lt;html&gt;
    &lt;head&gt;
        &lt;meta http-equiv=&quot;Content-Type&quot; content=&quot;text/html; charset=UTF-8&quot;&gt;
        &lt;title&gt;Shout Box | Guest Book Simple Script&lt;/title&gt;
        &lt;link rel=&quot;stylesheet&quot; type=&quot;text/css&quot; href=&quot;/styles/styles.css&quot;&gt;
    &lt;/head&gt;
    &lt;body&gt;
        &lt;?php
        if ($error !== false):
            ?&gt;
            &lt;div id=&quot;error&quot;&gt;&lt;?php echo $error; ?&gt;&lt;/div&gt;
            &lt;?php
        endif;
        ?&gt;
        &lt;div id=&quot;listing&quot;&gt;
            &lt;?php
            if (!empty($contents)) {
                foreach ($posts as $post):
                    ?&gt;
                    &lt;p class=&quot;post&quot;&gt;
                        &lt;b&gt;&lt;?php echo $post['postingUser']; ?&gt; &lt;/b&gt; 
                        (@&lt;?php echo $post['postingTime']; ?&gt;)&lt;br&gt;
                        &lt;?php echo $post['postedMessage']; ?&gt;
                    &lt;/p&gt;
                    &lt;?php
                endforeach;
            } else {
                echo 'Nothing has been Posted. Be the first to post!';
            }
            ?&gt;
        &lt;/div&gt;
        &lt;div id=&quot;form&quot;&gt;
            &lt;form action=&quot;&lt;?php echo basename(__FILE__); ?&gt;&quot; method=&quot;post&quot;&gt;
                &lt;label for=&quot;posting_user&quot;&gt;Username&lt;/label&gt;
                &lt;input type=&quot;text&quot; name=&quot;posting_user&quot; size=&quot;20&quot; &lt;?php if (isset($_POST['posting_user']))
                echo 'value=&quot;' . $_POST['posting_user'] . '&quot;';
            ?&gt;&gt; 
                &lt;label for=&quot;posting_site&quot;&gt;Site (Without http://)&lt;/label&gt;
                &lt;input type=&quot;text&quot; name=&quot;posting_site&quot; size=&quot;20&quot; &lt;?php if (isset($_POST['posting_user']))
                           echo 'value=&quot;' . $_POST['posting_site'] . '&quot;';
            ?&gt;&gt; 
                &lt;label for=&quot;posting_message&quot;&gt;Message&lt;/label&gt;
                &lt;textarea name=&quot;posting_message&quot; rows=&quot;5&quot; cols=&quot;20&quot;&gt; &lt;?php if (isset($_POST['posting_user']))
                           echo $_POST['posting_message'];
            ?&gt;&lt;/textarea&gt;
                &lt;input type=&quot;submit&quot; name=&quot;submit&quot; value=&quot;Post!&quot;&gt;
            &lt;/form&gt;
        &lt;/div&gt;
        &lt;a href=&quot;http://www.htmlandphp.com&quot; title=&quot;HTML and PHP Resources&quot; style=&quot;font-size: .5em;color:#999999;text-decoration:none;&quot;&gt;Shout-Box Script From HTMLandPHP.com&lt;/a&gt;
    &lt;/body&gt;
&lt;/html&gt;</code></pre></p>
<h4>/process/write.php</h4>
<p>This file is used to write new post to the data file. The file is loaded every time the script is called. When loaded the script checks to see if the form has been posted. If the form has not been posted it does nothing, if the form has been posted, then it processes the input, trimming extra white space, converting commas to their special character code and converting html entities to their html code equivalents.</p><pre class="crayon-plain-tag"><code>&lt;?php

$error = false;
if (isset($_POST['posting_user'])) {
    $postUser = trim($_POST['posting_user']);
    $postURL = trim($_POST['posting_site']);
    $postMessage = trim($_POST['posting_message']);

    if (($postUser != '') AND ($postMessage != '')) {
        $postUser = str_replace(',', '&amp;#44;', htmlentities($postUser));
        if (!empty($postURL)) {
            $postingUser = '&lt;a href=&quot;http://' . urlencode($postURL) . '&quot; target=&quot;_blank&quot;&gt;' . $postUser . '&lt;/a&gt;';
        } else {
            $postingUser = $postUser;
        }

        $postingTime = time();
        $postedMessage = str_replace(array(','), '&amp;#44;', htmlentities($postMessage));
        
        $line = $postingUser . ',' . $postingTime . ',' . $postedMessage .&quot;\n&quot;;

        $fileHandle = fopen($dataFile, 'a');
        if (!fwrite($fileHandle, $line)) {
            $error = 'Could not write to file, try again.';
        }
        fclose($fileHandle);

        // Delete post data so that fields do no populate again
        unset($_POST);
    } else {
        $error = 'Username and message are required!';
    }
}</code></pre></p>
<h4>/process/read.php</h4>
<p>The read.php is used to read information from the file specified in index.php. If the file does not exist or if the file is empty, it displays an appropriate message. If the file is not empty, the script processes the file, line by line, and splits the data at every comma. The data stored in the data file is username, followed by a unix time stamp and the message in the third position.</p><pre class="crayon-plain-tag"><code>&lt;?php

/*
 * Read the data stored in $dataFile if it exists!
 */
$contents = file_exists($dataFile) ? file_get_contents($dataFile) : '';

// If the file does not exits then there is no need to break up any information
if (!empty($contents)) {
    $lines = explode(&quot;\n&quot;, $contents);

    $posts = array();
    foreach ($lines as $line) {
        $parts = explode(',', $line);
        // Check to see if the line was more than a single element.
        if (count($parts) &gt; 1) {
            $posts[] = array('postingUser' =&gt; $parts[0],
                'postingTime' =&gt; date('m/d/Y H:m', $parts[1]),
                'postedMessage' =&gt; $parts[2]);
        }
    }
}</code></pre></p>
<h4>/styles/styles.css</h4>
<p>The styles.css is used to control the look of the page and layout of elements. It is a plain CSS file.</p><pre class="crayon-plain-tag"><code>html,
body {
    font-family: sans-serif;
    font-size: 12px;
}

label {
    float: left;
    clear: both;
    font-weight: bolder;
    color: #ffffff;
}

input,
textarea {
    border: solid 1px #343434;
    float: left;
    clear: both;
    width:200px;
}
div#error {
    padding:5px;
    font-weight: bolder;
    color: #FFF;
    background-color: #FF8888;
    width: 210px;
    border:solid 1px #FF0000;
}
div#listing{
    height: 250px;
    width: 210px;
    overflow: auto;
}

p.post {
    font-size: 1em;
    padding:5px;
    border:solid #AAA 1px;
}

div#form {
    background-color: #AAA;
    overflow:auto;
    padding:5px;
    width: 210px;
}</code></pre></p>
<p><a href="http://www.htmlandphp.com" title="Simple easy to follow html and php video tutorials.">Visit www.HTMLandPHP.com for more information!</a></p>]]></content:encoded>
			<wfw:commentRss>http://www.htmlandphp.com/scripts/simple-php-flat-file-shoutbox.html/feed</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
		<item>
		<title>205: Introduction to If-Else Conditionals in PHP</title>
		<link>http://www.htmlandphp.com/beginner-php/introduction-to-if-else-conditionals-in-php.html</link>
		<comments>http://www.htmlandphp.com/beginner-php/introduction-to-if-else-conditionals-in-php.html#comments</comments>
		<pubDate>Sun, 18 Dec 2011 00:11:37 +0000</pubDate>
		<dc:creator>Bladymir</dc:creator>
				<category><![CDATA[Beginner PHP]]></category>
		<category><![CDATA[Start Writing PHP]]></category>

		<guid isPermaLink="false">http://www.htmlandphp.com/?p=326</guid>
		<description><![CDATA[<p>Introduction In programming conditionals are the constructs that control flow of a program. Conditional constructs allow a program to have logic that enables decision making. Conditional construct in PHP include if, elseif, and else. The if and elseif are followed by &#8230; <a href="http://www.htmlandphp.com/beginner-php/introduction-to-if-else-conditionals-in-php.html">Continue reading <span class="meta-nav">&#8594;</span></a></p><p><a href="http://www.htmlandphp.com" title="Simple easy to follow html and php video tutorials.">Visit www.HTMLandPHP.com for more information!</a></p>]]></description>
			<content:encoded><![CDATA[<h3>Introduction</h3>
<p>In programming conditionals are the constructs that control flow of a program. Conditional constructs allow a program to have logic that enables decision making.</p>
<p>Conditional construct in PHP include <strong><em>if</em>, <em>elseif</em></strong>, and <strong><em>else</em>.</strong> The <em><strong>if</strong></em> and <em><strong>elseif</strong></em> are followed by one or more expressions that can be evaluated to a Boolean value. The else is not followed by a boolean expression, but simply by a block of code that will be executed in the case that the other Booleans expressions are false.</p>
<h3>Boolean Expression</h3>
<p>A Boolean expression is simply a set of one or more comparisons that result in a <strong><em>true</em></strong> or <strong><em>false</em></strong> value.</p>
<h3>Comparison Operators</h3>
<p>Comparison Operators are simply operators that compare two values. You can compare a variable to a value or two variables to each other. The operators are used in between the two values we are comparing and return a Boolean value, a <strong><em>true</em></strong> or <strong><em>false</em></strong>.</p>
<table>
<thead>
<tr>
<th>Operator</th>
<th>Description</th>
<th>Example</th>
<th>Boolean Value of Example</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align: center;">==</td>
<td>Checks for equality</td>
<td>&#8220;abc&#8221; == &#8220;abc&#8221;</td>
<td>true</td>
</tr>
<tr>
<td style="text-align: center;">!=</td>
<td>Checks for unequality</td>
<td>&#8220;abc&#8221; != &#8220;abc&#8221;</td>
<td>false</td>
</tr>
<tr>
<td style="text-align: center;">&gt;</td>
<td>Greater than</td>
<td>1 &gt; 2</td>
<td>false</td>
</tr>
<tr>
<td style="text-align: center;">&lt;</td>
<td>Less than</td>
<td>1 &lt; 2</td>
<td>true</td>
</tr>
<tr>
<td style="text-align: center;">&gt;=</td>
<td>Greater than or equal</td>
<td>1 &gt;= 2</td>
<td>false</td>
</tr>
<tr>
<td style="text-align: center;">&lt;=</td>
<td>Less than or equal</td>
<td>1 &lt;= 2</td>
<td>true</td>
</tr>
<tr>
<td style="text-align: center;">===</td>
<td>Identity -<br />
Checks value and data type</td>
<td>0 === false</td>
<td>false<br />
<em>(NOTE: &#8220;0 == false&#8221; results in true)</em></td>
</tr>
<tr>
<td style="text-align: center;">!==</td>
<td>Not an Identity -<br />
Checks value and data type</td>
<td>0 !== false</td>
<td>true<br />
<em>(NOTE: &#8220;0 != false&#8221; results in false)</em></td>
</tr>
</tbody>
</table>
<p>example_comparison_operators.php</p><pre class="crayon-plain-tag"><code>&lt;?php
$string1 = &quot;abc&quot;;
$string2 = &quot;def&quot;;

$int1 = 100;
$float1 = 100.0;

// Checks for Equality
var_dump($string1 == $string2); // false

// Checks for Inequality
var_dump($string1 != $string2); // true

// Left value greater than right value?
var_dump($int1 &gt; 100);  // False

// Left value is less than right value?
var_dump($int1 &lt; 100);  // False

// Left value greater than OR equal to right value?
var_dump($int1 &gt;= 100);  // True

// Left value is less than OR equal to right value?
var_dump($int1 &lt;= 100);  // True

// Check for identity, check value and type
var_dump($int1 === $float1); // False

// Check for NOT identity, check value and type
var_dump($int1 !== $float1);  // True</code></pre></p>
<h3>Joining Multiple Boolean Expressions</h3>
<p>Its possible to have multiple Boolean expressions in order to match a set of conditions. In such a case the <strong><em>AND </em></strong>and <strong><em>OR</em></strong> key words or <strong><em>&amp;&amp;</em></strong> for <strong><em>AND</em></strong> and <em><strong>||</strong></em> for <strong><em>OR</em></strong> symbols can be used to join multiple expressions. <strong><em>AND</em></strong> returns <em><strong>true</strong></em> if the expressions being joined are both <em><strong>true</strong></em>. In contrast <strong><em> OR</em></strong> returns a true value when <em>at least one</em> of the expressions is <em><strong>true</strong></em>. It should be noted also that you can use any combination of <strong><em>AND</em></strong> and <strong><em>OR</em></strong> and group pairs of expressions with parenthesis  to meet more specific criteria in your scripts.</p>
<p>example_and_or.php</p><pre class="crayon-plain-tag"><code>&lt;?php
$var1 = 100;
$var2 = &quot;abc&quot;;

// Using AND
var_dump($var1 == 100 AND $var2 == &quot;abc&quot;); // True
var_dump($var1 == 200 AND $var2 == &quot;abc&quot;); // False

// Using OR
var_dump($var1 == 100 OR $var2 == &quot;abc&quot;); // True
var_dump($var1 == 200 OR $var2 == &quot;abc&quot;); // True

// Using AND and OR
var_dump(($var1 == 100 OR $var2 == &quot;def&quot;) AND ($var1 == 200 OR $var2 == &quot;abc&quot;)); // True
var_dump(($var1 == 100 AND $var2 == &quot;abc&quot;) OR ($var1 == 200 AND $var2 == &quot;abc&quot;)); // True</code></pre></p>
<h3>Syntax</h3>
<h4>The &#8220;if&#8221; Statement</h4>
<p>The <strong><em>if</em></strong> statement should be followed by a Boolean expression encased in parenthesis in order to be parse correctly. After the parenthesis you can define a block of code to execute by wrapping any number of lines between curly brackets. You can omit the curly brackets if you only have a single line of code after the if statement. In the case that you have multiple lines of code that you want to execute but omit the curly brackets, only the first line is considered part of the <em><strong>if</strong></em>.</p>
<p>example_syntax_if.php</p><pre class="crayon-plain-tag"><code>&lt;?php
$var1 = &quot;cool&quot;;

if ($var1 == &quot;Cool&quot;) { 
    // FALSE - Comparison is case sensative
    // This will not execute since the expression is false
    echo &quot;Case InSensative?&quot;;
}

if ($var1 == &quot;cool&quot;) {
    // TRUE - The expression is a match in value.
    echo &quot;CASE SENSATIVE!&quot;;
}</code></pre></p>
<h4>The &#8220;elseif&#8221; and &#8220;else if&#8221; Statements</h4>
<p>The &#8220;<strong><em>elseif&#8221;</em></strong> and &#8220;<strong><em>else if&#8221;</em></strong> statements work in a similar fashion to the &#8220;<em><strong>if&#8221;</strong></em>, they are followed by a Boolean expression encased in parenthesis and a line or a block of code that will get executed.</p>
<p>The only time an <em><strong>&#8220;</strong></em><strong><em>else if&#8221;</em></strong> statement gets executed is when the condition inside the <strong><em>&#8220;if&#8221;</em></strong> statement was false.</p>
<p>Note that you are able to have multiple <strong><em>&#8220;else if</em><em>&#8220;</em></strong> statements following an if. The parser will check each of the statements sequential until a true statement is found.</p>
<p>example_if_elseif.php</p><pre class="crayon-plain-tag"><code>&lt;?php
$var1 = &quot;cool&quot;;

if ($var1 == &quot;Cool&quot;) { 
    // FALSE - Comparison is case sensative
    // Parser moves to next &quot;if&quot; in the sequence
    echo &quot;Case InSensative?&quot;;
} else if ($var1 == &quot;not-cool&quot;) {
    // FALSE - Comparison is not a match
    // Parser moves to next &quot;if&quot; in the sequence
    echo &quot;Not A Match&quot;;
} else if ($var1 == &quot;cool&quot;) {
    // TRUE - Comparison is a match
    echo &quot;Finally A Match&quot;;
}</code></pre></p>
<h3>The &#8220;else&#8221; Statement</h3>
<p>The <strong><em>&#8220;else&#8221;</em></strong> statement is the final step in a conditional statement. This is an optional component of the conditionals as it functions as a fallback option in the case that none of the other options match. The else does not have a Boolean expression, but it does need a line or block of code that it should execute in the case none of the <strong><em>&#8220;if&#8221;</em></strong> or <strong><em>&#8220;else if&#8221;</em></strong> statements matched. If you do not have any code for the else, you can omit it entirely like the examples above.</p>
<p>example_if_elseif_else.php</p><pre class="crayon-plain-tag"><code>&lt;?php
$var1 = &quot;cool&quot;;

if ($var1 == &quot;Cool&quot;) { 
    // FALSE - Comparison is case sensative
    // Parser moves to &quot;else if&quot; in the sequence
    echo &quot;Case InSensative?&quot;;
} else if ($var1 == &quot;not-cool&quot;) {
    // FALSE - Comparison is not a match
    // Parser moves to next &quot;else if&quot; in the sequence
    echo &quot;Not A Match&quot;;
} else if ($var1 == &quot;warm&quot;) {
    // FALSE - Comparison is not a match
    // Parser moves to &quot;else&quot;  in the sequence
    echo &quot;Not A Match Again&quot;;
} else {
    echo &quot;Not Match was Found, so I echo this!&quot;;
}</code></pre></p>
<h3>Summary</h3>
<p>In summary the if-else constructs in PHP allow us to control flow of the script in order to execute specific piece of code depending on the value of variables we specify. You can use the <em><strong>&#8220;if&#8221;</strong></em> construct in conjunction with <em><strong>&#8220;elseif&#8221;</strong></em> and <em><strong>&#8220;else&#8221;</strong></em> or use it independently. Note that the expression following the <em><strong>&#8220;if&#8221;</strong></em> or <em><strong>&#8220;else-if&#8221;</strong></em> is always evaluated to a Boolean value.</p>
<h3>Questions or Concerns?</h3>
<p>If you happen to have any questions, concerns or corrections please let us know in the comment area or you can reach us at <strong>php@htmlandphp.com</strong></p>
<p><a href="http://www.htmlandphp.com" title="Simple easy to follow html and php video tutorials.">Visit www.HTMLandPHP.com for more information!</a></p>]]></content:encoded>
			<wfw:commentRss>http://www.htmlandphp.com/beginner-php/introduction-to-if-else-conditionals-in-php.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>204: Introduction to Data Types</title>
		<link>http://www.htmlandphp.com/beginner-php/204-introduction-to-data-types.html</link>
		<comments>http://www.htmlandphp.com/beginner-php/204-introduction-to-data-types.html#comments</comments>
		<pubDate>Sat, 17 Dec 2011 15:26:11 +0000</pubDate>
		<dc:creator>Bladymir</dc:creator>
				<category><![CDATA[Beginner PHP]]></category>
		<category><![CDATA[Start Writing PHP]]></category>

		<guid isPermaLink="false">http://www.htmlandphp.com/?p=284</guid>
		<description><![CDATA[<p>Introduction PHP is a loosely typed programming language. Although PHP is loosely typed it is still necessary to distinguish the type of data that is stored by a variable at a given time. The major data types that operate in PHP are &#8230; <a href="http://www.htmlandphp.com/beginner-php/204-introduction-to-data-types.html">Continue reading <span class="meta-nav">&#8594;</span></a></p><p><a href="http://www.htmlandphp.com" title="Simple easy to follow html and php video tutorials.">Visit www.HTMLandPHP.com for more information!</a></p>]]></description>
			<content:encoded><![CDATA[<h3>Introduction</h3>
<p>PHP is a loosely typed programming language. Although PHP is loosely typed it is still necessary to distinguish the type of data that is stored by a variable at a given time.</p>
<p>The major data types that operate in PHP are strings, integers, floating points(decimals), arrays and for lack of a better description, objects.</p>
<h3>Checking for Output</h3>
<p>In order to better understand the data types our variables are holding we are going to make use of the <em><a title="var_dump php docs" href="http://www.php.net/manual/en/function.var-dump.php" target="_blank">var_dump()</a></em> function that is available in PHP. The <em><a title="var_dump php doc" href="http://www.php.net/manual/en/function.var-dump.php" target="_blank">var_dump()</a></em> function allows us to see what type of data and what value the data has by sending it to our browsers.</p>
<h3>Strings</h3>
<p>Strings are simply a collection of numbers, letters and/or symbols. Strings are typically wrapped in single or double quotes. Strings simply store text.</p>
<h4>Note On Quotation Marks</h4>
<p>Strings enclosed by double quotes are parsed for embedded variables and special characters. Special characters are characters such as new line (\n), tab (\t) and other double quotes, just to name a few.</p>
<p>Strings enclosed by single quotes are literal strings that do not get parsed again, the string will literally be what it was defined as.</p>
<p>When you define a string it is important to note that after you have decided on what type of quotes to use, you will have to escape that type of quote with the backslash character, if you decide you need to use it as part of the string.</p>
<p>For example, a string encased in double quotes will need to have a backslash before the inner quote so that it gets rendered as a double quote.</p>
<p>Failing to escape the double quote inside will result in PHP not being able to run your script due to parsing errors. PHP will parse the inner quote as if it was the end of the string and the remainder of the string will be parsed as &#8220;invalid PHP&#8221;. The same idea applies to single quotes inside a string wrapped by single quotes.</p>
<p>A string containing double quotes, wrapped in single quotes does not need to be escaped. The same applies to the reverse situation.</p>
<p>example_string.php</p><pre class="crayon-plain-tag"><code>&lt;?php
$variable = 'Hello World!\n'; // String Literal
var_dump($variable);

$variable = 'Hello \'World\'!\n'; // String Literal
var_dump($variable);

$variable = 'Hello &quot;World!&quot;\n'; // String Literal
var_dump($variable);

//Change value of variable
$variable = &quot;Hello World!\n&quot;; // String parsed for special characters
var_dump($variable);

$variable = &quot;Hello \&quot;World!\&quot;\n&quot;; // String parsed for special characters
var_dump($variable);

$variable = &quot;Hello 'World!'\n&quot;; // String parsed for special characters
var_dump($variable);</code></pre></p>
<h3>Integers and Floating Points</h3>
<p>In PHP there are two types of data that hold numerical values, integers and floating points.</p>
<p>Integers serve to hold whole numbers. Integers are commonly used to hold counts, id numbers, or indexes of an array.</p>
<p>Floating points are what we more generally refer to as decimals. Floating points occur whenever the numerical value will not be a whole number.</p>
<p>It should be noted that the switch between integers to floating points is handled by the PHP interpreter.</p>
<p>example_integers_floats.php </p><pre class="crayon-plain-tag"><code>&lt;?php
$variable = 10;
var_dump($variable);

$variable = 10.0;
var_dump($variable);</code></pre></p>
<h3>Boolean</h3>
<p>Boolean is simply a value of true or false. The possible values that it can hold are assigned with either of the two keywords, <em>TRUE</em> and <em>FALSE</em>. The keywords are case insensitive, any capitalization will translate appropriately. Boolean are an abstraction that is used extensively in conditionals and loops.</p>
<p>Note on Booleans: The PHP interpreter will interpret any zero or empty value as false and any non empty or non zero value as true. What this means is that the true and false values can be mimicked by using zero and one or an empty string and a non empty string to represent <em>FALSE</em> and <em>TRUE</em>.</p>
<p>example_boolean.php </p><pre class="crayon-plain-tag"><code>&lt;?php
$variable = true;
var_dump($variable);

$variable = false;  //Change value of variable
var_dump($variable);</code></pre></p>
<h3>Arrays</h3>
<p>In the simplest terms, arrays can be seen as a list or set of data. Arrays in PHP can hold any type of data within, so arrays can hold a collection of strings, intergers, floats, boolean, objects or other arrays. Arrays in PHP are not restricted to holding just one type of data, they can hold any combination of data.</p>
<p>Arrays are typically used to hold sets of data and it is very common to populate them within loops.</p>
<p>example_array.php</p><pre class="crayon-plain-tag"><code>&lt;?php
// Arrays with indexes starting at 0
$variable = array(); // empty array
var_dump($variable);

$variable = array('a','b','c'); // array of strings
var_dump($variable);

$variable = array('a', 1 , 1.0, array(1,2,3)); // array of diff data types
var_dump($variable);

// Array with index's(key's) mapped to values
$variable = array('name' =&gt; 'Joe', 'age' =&gt; 21); // array of diff data types
var_dump($variable);</code></pre></p>
<h3>Objects</h3>
<p>Objects are an advanced topic in PHP. Objects are part of PHP&#8217;s object oriented features, and in simplest terms they are a custom data type that we can define. Objects are a collection of methods(functions) and member variables(variables belonging to the object) that represent some abstraction. Unfortunately we will not do anything with objects until we get to our advanced PHP tutorials.</p>
<h3>Summary</h3>
<p>Even though PHP is a loosely typed language there is still a need to consider the type of data that is being held in variables. The var_dump() function helps us to determine what&#8217;s in our variables and is a common tool used to track down issues with why script execution may not be occurring as expected.</p>
<p><strong>Strings</strong> are a collection of characters.</p>
<p><strong>Integers</strong> are whole numbers.</p>
<p><strong>Floating points</strong> are decimal numbers.</p>
<p><strong>Boolean</strong> value are either true or false.</p>
<p><strong>Arrays</strong> are sets of other data types including other arrays.</p>
<p><strong>Objects</strong> are a custom data type that is an abstract representation of a set of data.</p>
<p>&nbsp;</p>
<p><a href="http://www.htmlandphp.com" title="Simple easy to follow html and php video tutorials.">Visit www.HTMLandPHP.com for more information!</a></p>]]></content:encoded>
			<wfw:commentRss>http://www.htmlandphp.com/beginner-php/204-introduction-to-data-types.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
<!-- This Quick Cache file was built for (  www.htmlandphp.com/feed ) in 1.80535 seconds, on May 20th, 2012 at 5:47 pm UTC. -->
<!-- This Quick Cache file will automatically expire ( and be re-built automatically ) on May 20th, 2012 at 6:47 pm UTC -->
