<?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"
	>

<channel>
	<title>php</title>
	<atom:link href="http://php.w3clubs.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://php.w3clubs.com</link>
	<description>PHP tutorials and articles</description>
	<pubDate>Sun, 10 Aug 2008 09:09:58 +0000</pubDate>
	<generator>http://wordpress.org/?v=2.5.1</generator>
	<language>en</language>
			<item>
		<title>Working with files - reading and writing</title>
		<link>http://php.w3clubs.com/php-tutorial/working-with-files-reading-and-writing/</link>
		<comments>http://php.w3clubs.com/php-tutorial/working-with-files-reading-and-writing/#comments</comments>
		<pubDate>Sun, 10 Aug 2008 09:02:27 +0000</pubDate>
		<dc:creator>admin</dc:creator>
		
		<category><![CDATA[PHP Tutorial]]></category>

		<guid isPermaLink="false">http://php.w3clubs.com/?p=25</guid>
		<description><![CDATA[Saving data on the server is probably one of the reasons you may have decided you need PHP in addition to all the client side technologies - HTML, JavaScript, CSS. You do need a server-side technology in order to write to the server. You can save to a database, or just to plain old text [...]]]></description>
			<content:encoded><![CDATA[<p>Saving data on the server is probably one of the reasons you may have decided you need PHP in addition to all the client side technologies - HTML, JavaScript, CSS. You do need a server-side technology in order to write to the server. You can save to a database, or just to plain old text files. Let's learn how.</p>
<h3>A text file</h3>
<p>Assuming you have your <a href="/php-tutorial/installing-php/">server setup as described before</a>, create a text file <code>C:\mywebstuff\htdocs\php-tutorial\file.txt</code> with the following contents:</p>
<pre>
this is text file
second line of text
and a third
</pre>
<h3>File info</h3>
<p>Now let's test a few functions that return information about a file. The functions in question are:</p>
<ul>
<li><a href="http://php.net/file_exists">file_exists()</a> - returns TRUE is the file exists</li>
<li><a href="http://php.net/filesize">filesize()</a> - returns the file size in bytes</li>
<li><a href="http://php.net/is_dir">is_dir()</a> - returns TRUE when given a directory</li>
<li><a href="http://php.net/is_file">is_file()</a> - returns TRUE when given a file </li>
<li><a href="http://php.net/filemtime">filemtime()</a> - returns a timestamp of when the file was modified</li>
<li><a href="http://php.net/realpath">realpath()</a> - returns the actual path on the machine</li>
</ul>
<p>Let's see an example - populating an array of file info using those functions.</p>
<pre>
$file = 'file.txt';

$fileinfo = array(
    'file_exists()' =&gt; file_exists($file),
    'filesize()'    =&gt; filesize($file),
    'is_dir()'      =&gt; is_dir($file),
    'is_file()'     =&gt; is_file($file),
    'filemtime()'   =&gt; date('Y-m-d h:i:s a', filemtime($file)),
    'realpath()'    =&gt; realpath($file),
);
print_r($fileinfo);
</pre>
<p>This will return:</p>
<blockquote>
<pre>
Array
(
    [file_exists()] =&gt; 1
    [filesize()] =&gt; 51
    [is_dir()] =&gt;
    [is_file()] =&gt; 1
    [filemtime()] =&gt; 2007-09-24 12:08:53 am
    [realpath()] =&gt; C:\mywebstuff\htdocs\php-tutorial\file.txt
)
</pre>
</blockquote>
<p>Another useful function is <a href="http://php.net/pathinfo">pathinfo()</a>, it returns an array of information about the file, based on the path. This function actually works with file locations, regardless if a file exists at this location or this is just a made-up path.</p>
<pre>
$realpath = realpath($file);
$info = pathinfo($realpath);
print_r($info);
</pre>
<p>In the code above we called <code>realpath()</code> first, so that we have a more detailed path to pass to <code>pathinfo()</code>. The result will be:</p>
<blockquote>
<pre>
Array
(
    [dirname] =&gt; C:\mywebstuff\htdocs\php-tutorial
    [basename] =&gt; file.txt
    [extension] =&gt; txt
    [filename] =&gt; file
)
</pre>
</blockquote>
<h3>Reading the contents of a file</h3>
<p>A simple function to grab the contents of a file, is called <a href="http://php.net/file">file()</a>. It reads a file and returns an array where each element is a line from the file. The array also contains the end-of-line characters, so if we use <code>var_dump()</code> to print out the contents of the returned array, you'll see that the closing quote for each element is on a second line.</p>
<pre>
$contents = file($file);
var_dump($contents);
</pre>
<p>This prints:</p>
<blockquote>
<pre>
array(3) {
  [0]=&gt;
  string(19) "this is text file
"
  [1]=&gt;
  string(21) "second line of text
"
  [2]=&gt;
  string(11) "and a third"
}
</pre>
</blockquote>
<p>You can print individual lines if you wish:</p>
<pre>
echo "the second line starts...", $contents[1], "...and ends.";
</pre>
<p>The result:</p>
<blockquote>
<pre>
the second line starts...second line of text
...and ends.
</pre>
</blockquote>
<p>The function <a href="http://php.net/trim">trim()</a> comes in handy when you want to strip out the extra end-of-line characters.</p>
<pre>
echo "the second line starts...", trim($contents[1]), "...and ends.";
</pre>
<p>The above will print:</p>
<blockquote>
<pre>
the second line starts...second line of text...and ends.
</pre>
</blockquote>
<h3>Printing out the file contents</h3>
<p>A very simple way to print out the whole file already read by <code>file()</code> is to <code>implode()</code> the array of lines:</p>
<pre>
echo implode('', $contents);
</pre>
<p>This prints the whole file:</p>
<blockquote>
<pre>
this is text file
second line of text
and a third
</pre>
</blockquote>
<p>Another way to do the same is by using <a href="http://php.net/file_get_contents">file_get_contents()</a>.</p>
<pre>
echo file_get_contents($file);
</pre>
<p>This again prints the whole file.</p>
<blockquote>
<pre>
this is text file
second line of text
and a third
</pre>
</blockquote>
<h3>Writing to a file</h3>
<p>The corresponding to <code>file_<em>get</em>_contents()</code> function is <code><a href="http://php.net/file_put_contents">file_<em>put</em>_contents()</a></code>. It takes a filename and a string and writes the string into the file.</p>
<p>Let's see an example where we read <code>file.txt</code> into a string, add some more lines to the string (delimited by the new line character \n) and write the result to a new file <code>file2.txt</code>. Finally we print out the contents of <code>file2.txt</code> to validate that everything was written OK.</p>
<pre>
$cnt = file_get_contents($file);
$cnt .= "\nA forth line";
$cnt .= "\nAnd a fifth line";
file_put_contents('file2.txt', $cnt);
echo file_get_contents('file2.txt');
</pre>
<p>This prints the new file:</p>
<blockquote>
<pre>
this is text file
second line of text
and a third
A forth line
And a fifth line
</pre>
</blockquote>
<h3>Remote files</h3>
<p>The functions <code>file()</code> and <code>file_get_contents()</code> that we used to read a file can also be used to read a remote file (if allowed by the PHP configuration). Let's see a short example where we read the page located at yahoo.com and print some random line.</p>
<pre>
$contents = file('http://www.yahoo.com');
echo htmlspecialchars($contents[123]);
</pre>
<p>Line 123 happens to be the following at the time of writing this:</p>
<blockquote>
<pre>
&lt;a href="r/0z"&gt;Local&lt;/a&gt;&lt;br&gt;
</pre>
</blockquote>
<h3>Older PHP versions</h3>
<p>The handy pair of functions <code>file_get_contents()</code> and <code>file_put_contents()</code> were introduced at some point in PHP, but were not there from the very beginning. If you happen to be stuck with an older PHP version, you might need to take a look at these functions to achieve the same:</p>
<ul>
<li><a href="http://php.net/fopen">fopen()</a>, <a href="http://php.net/fread">fread()</a> and <a href="http://php.net/fclose">fclose()</a> instead of <code>file_get_contents()</code></li>
<li>fopen(), <a href="http://php.net/fwrite">fwrite()</a> and fclose() instead if <code>file_put_contents()</code></li>
</ul>
<h3>Summary</h3>
<p>These were only some of the various functions PHP hasd to offer when working with files. For more, point your trusted browser to <a href="http://php.net/filesystem">http://php.net/filesystem</a></p>
]]></content:encoded>
			<wfw:commentRss>http://php.w3clubs.com/php-tutorial/working-with-files-reading-and-writing/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Project &#8220;Ragtime&#8221;: dynamic URLs</title>
		<link>http://php.w3clubs.com/php-tutorial/project-ragtime-dynamic-urls/</link>
		<comments>http://php.w3clubs.com/php-tutorial/project-ragtime-dynamic-urls/#comments</comments>
		<pubDate>Sun, 10 Aug 2008 09:01:58 +0000</pubDate>
		<dc:creator>admin</dc:creator>
		
		<category><![CDATA[PHP Tutorial]]></category>

		<guid isPermaLink="false">http://php.w3clubs.com/?p=24</guid>
		<description><![CDATA[Now that you know about arrays and GET variables, let's review our little project site and see what can be improved.
What we have so far
In case you skipped the previous two stages of the Ragtime web-site development, check out here and here and the last demo here.
In the previous implementations we had some PHP scripts [...]]]></description>
			<content:encoded><![CDATA[<p>Now that you know about arrays and GET variables, let's review our little project site and see what can be improved.</p>
<h3>What we have so far</h3>
<p>In case you skipped the previous two stages of the Ragtime web-site development, check out <a href="/php-tutorial/project-ragtime-your-first-php-site/">here</a> and <a href="/php-tutorial/project-ragtime-variable-titles/">here</a> and the last <a href="http://www.w3clubs.com/w3clubs-examples/ragtime2/">demo here</a>.</p>
<p>In the previous implementations we had some PHP scripts (like aboutus.php) that also include common parts of the pages - header, footer, menu. One kind of annoying this is that for every new page, you have to copy/paste some PHP code and repeat it in every page. This is the code that includes header.inc.php and footer.inc.php. Let's improve this.</p>
<h3>The new file layout</h3>
<p>In the new implementation, we remove any PHP code from all content pages (contact.php, aboutus.php, etc). Since these files now will contain only HTML, it's no longer necessary to have them as PHP scripts, so we'll rename them to *.html. So we'll have these static content pages:</p>
<ul>
<li>products.html (was products.php)</li>
<li>aboutus.html (was aboutus.php)</li>
<li>contact.html (was contact.php)</li>
<li>home.html - This is the home page, was index.php</li>
</ul>
<p>We'll also have the same include files, although they'll be slightly changed:</p>
<ul>
<li>header.inc.php</li>
<li>footer.inc.php</li>
<li>menu.inc.php</li>
</ul>
<p>The big changes are in index.php, it will now serve as sort of a controller script that takes user input and decides which files to include. The user input will be received through a GET parameter named "page". So we'll have the following pages with the corresponding URLs:</p>
<table>
<tr>
<th>
      Page
    </th>
<th>
      URL
    </th>
</tr>
<tr>
<td>
      Home (index) page
    </td>
<td>
      index.php?page=home
    </td>
</tr>
<tr>
<td>
      Products
    </td>
<td>
      index.php?page=products
    </td>
</tr>
<tr>
<td>
      Contact Us
    </td>
<td>
      index.php?page=contact
    </td>
</tr>
<tr>
<td>
      About Us
    </td>
<td>
      index.php?page=aboutus
    </td>
</tr>
</table>
<h3>The content pages</h3>
<p>These are now really simple static HTML files.</p>
<p>home.html</p>
<pre>
&lt;h1&gt;Welcome to Ragtime!&lt;/h1&gt;

&lt;p&gt;Select a link from our nice menu&lt;/p&gt;
</pre>
<p>products.html</p>
<pre>
&lt;h1&gt;Products&lt;/h1&gt;

&lt;p&gt;Check out our wide selection of tires. We have:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Winter tires&lt;/li&gt;
  &lt;li&gt;Summer tires&lt;/li&gt;
  &lt;li&gt;All-season tires&lt;/li&gt;
&lt;/ul&gt;
</pre>
<p>contact.html</p>
<pre>
&lt;h1&gt;Contact Us&lt;/h1&gt;

&lt;div id="hcard-Ragtime" class="vcard"&gt;
 &lt;a class="url fn" href="http://www.ragtimebg.com"&gt;Ragtime&lt;/a&gt;
 &lt;div class="adr"&gt;
  &lt;span class="locality"&gt;Sofia&lt;/span&gt;,
  &lt;span class="country-name"&gt;Bulgaria&lt;/span&gt;
 &lt;/div&gt;
 &lt;div class="tel"&gt;1-888-123-4567&lt;/div&gt;
&lt;/div&gt;
</pre>
<p>aboutus.html</p>
<pre>
&lt;h1&gt;About Us&lt;/h1&gt;

&lt;p&gt;This is the "about us" page, always very popular place.&lt;/p&gt;

&lt;p&gt;Our company was found in year 1467 by ...&lt;/p&gt;
</pre>
<h3>The index script</h3>
<p>This script index.php will do most of the work. The script starts by defining an array calles <code>$pages</code>. This array will hold information about all the pages in the site. It's an associative array and its keys are the page identifiers. Each page identifier has a corresponding array that has the keys <code>title</code> and <code>menu</code>. The <code>title</code> value will be used for the <code>&lt;title&gt;</code> tag and the <code>menu</code> value will be used for the navigation menu. If <code>menu</code> is missing, the value in <code>title</code> will be reused.</p>
<pre>
&lt;?php
$pages = array(
    'home' =&gt; array(
        'title' =&gt; 'Welcome to Ragtime!',
        'menu'  =&gt; 'Home'
    ),
    'products' =&gt; array(
        'title' =&gt; 'Products',
    ),
    'contact' =&gt; array(
        'title' =&gt; 'Contact us',
    ),
    'aboutus' =&gt; array(
        'title' =&gt; 'About us',
    ),
);
</pre>
<p>Next, we want to populate a value in a <code>$page</code> variable. This variable will hold the identifier of the page the user has requested. We check if the <code>$_GET['page']</code> input parameter has a value using the function <a href="http://php.net/empty">empty()</a>. If not, we default to the homepage.</p>
<pre>
// is there a page ID passed in GET
if (empty($_GET['page'])) {
    $page = 'home';
} else {
    $page = $_GET['page'];
}
</pre>
<p>Now that we have <code>$page</code> defined, let's validate its value. We expect that the regular user will just follow our links and will pass values for the <code>$_GET['page']</code> parameter such as "home", "products", etc. But there will be users that will try to play with this parameter, passing strange values. <a href="/php-tutorial/accepting-user-input-through-get/">"Never trust user input" is the mantra</a>, so we must validate. We do this by simply checking if the page ID passed by the user exists as a key in the pre-defined <code>$pages</code> array. If it does, we're fine, otherwise we reset <code>$page</code> to "home".</p>
<pre>
// is this a valid page ID
if (empty($pages[$page])) {
    $page = 'home';
}
</pre>
<p>Finally, we define a <code>$title</code> variable (to be reused in the <code>header.inc.php</code> for the <code>&lt;title&gt;</code> tag) and we include header, footer and the static content page that was requested. If for example the request was <code>index.php?page=aboutus</code>, we end up including <code>aboutus.html</code></p>
<pre>
// title of the page
$title = $pages[$page]['title'];

include 'header.inc.php';

include $page . '.html';

include 'footer.inc.php';
?&gt;
</pre>
<h3>Header and footer</h3>
<p>The header and the footer contain only repeating parts, common to all pages. </p>
<p><code>header.inc.php</code> uses the <code>$title</code> variable defined in index.php for the HTML title tag, it also uses the <code>$page</code> variable to set an ID attribute in the HTML body tag (we'll see why in a second). The header also includes <code>menu.inc.php</code>.</p>
<p>Here's the content of the <code>header.inc.php</code> include script</p>
<pre>
&lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"&gt;
&lt;html&gt;
&lt;head&gt;
  &lt;title&gt;Ragtime &amp;gt; &lt;?php echo $title; ?&gt;&lt;/title&gt;
  &lt;link rel="stylesheet" href="ragtime.css" type="text/css" /&gt;
&lt;/head&gt;
&lt;body id="page-&lt;?php echo $page; ?&gt;"&gt;

&lt;?php
include 'menu.inc.php';
?&gt;

&lt;div id="content"&gt;
</pre>
<p><code>footer.inc.php</code> only closes tags.</p>
<pre>
&lt;/div&gt;

&lt;/body&gt;
&lt;/html&gt;
</pre>
<h3>menu.inc.php</h3>
<p>In the <code>menu.inc.php</code> we simply loop through the <code>$pages</code> array (defined in index.php) in order to produce a list of menu items. To make the code a little bit more readable, we have a little template that is used for the LI tags. Then in every iteration of the loop we call the function <a href="http://php.net/str_replace">str_replace()</a> to replace the placeholders {PAGE} and {TITLE} with real values.</p>
<pre>
&lt;ul id="menu"&gt;
&lt;?php

$item_tpl = '&lt;li&gt;&lt;a href="index.php?page={PAGE}" id="menu-{PAGE}"&gt;{TITLE}&lt;/a&gt;&lt;/li&gt;';

foreach ($pages AS $key =&gt; $data) {

    $menu_item = str_replace('{PAGE}', $key, $item_tpl);
    if (!empty($data['menu'])) {
        $menu_item = str_replace('{TITLE}', $data['menu'], $menu_item);
    } else {
        $menu_item = str_replace('{TITLE}', $data['title'], $menu_item);
    }
    echo $menu_item;
} // end foreach
?&gt;
&lt;/ul&gt;
</pre>
<p>After this code is executed, the HTML code for the navigation menu will look like:</p>
<pre>
&lt;ul id="menu"&gt;
  &lt;li&gt;&lt;a href="index.php?page=home" id="menu-home"&gt;Home&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href="index.php?page=products" id="menu-products"&gt;Products&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href="index.php?page=contact" id="menu-contact"&gt;Contact us&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href="index.php?page=aboutus" id="menu-aboutus"&gt;About us&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
</pre>
<h3>Highlighting the current menu item</h3>
<p>As you see we defined an <code>id</code> attribute in the body tag (like "page-products") and also an <code>id</code> in the navigation menu. This allows the use of CSS in order to highlight the current menu item by using:</p>
<pre>
#page-aboutus #menu-aboutus,
#page-home #menu-home,
#page-products #menu-products,
#page-contact #menu-contact {
    background: CornflowerBlue;
}
</pre>
<p>So the navigation menu item will have a different color but only on the page that has the same id. It's a small trick that can help a lot to have CSS do some work instead of using an <code>if</code> in the PHP code.</p>
<h3>Demo and code</h3>
<ul>
<li><a href="http://www.w3clubs.com/w3clubs-examples/ragtime3/">Demo</a></li>
<li><a href="http://www.w3clubs.com/w3clubs-examples/ragtime3/ragtime3-dynamic-urls.zip">Code download</a></li>
</ul>
<h3>An SEO improvement with .htaccess</h3>
<p>The site is very nice now and have a bunch of static files (which can be edited by someone with HTML experience only, no PHP knowledge required). We use dynamic URLs and have a little framework to load the static files per user requested.</p>
<p>A potential issue is that it's believed that some search engines don't like dynamic URLs very much and sometimes ignore everything after the ? symbol. It's not quite clear how much of an issue that is, but why risk the search engine popularity of the site when we can quickly correct this, using URL rewrites.</p>
<p>I'm not going to describe the URL rewrites in detail here, but the idea is that Apache has this ability to turn some publicly visible URLs into others that can be used internally. In our case we want that a request to <code>home.html</code> to be treated the same as a request to <code>index.php?page=home</code>. To achieve this you create an .htacess file with the following contents:</p>
<pre>
Options +FollowSymLinks
RewriteEngine on
RewriteRule ^(.*).html$ index.php?page=$1
</pre>
<p>We also need to change the "template" we used in the menu.inc.php in order to produce the new type of URLs:</p>
<p><code>$item_tpl = '&lt;li&gt;&lt;a href="index.php?page={PAGE}" id="menu-{PAGE}"&gt;{TITLE}&lt;/a&gt;&lt;/li&gt;';</code></p>
<p>becomes </p>
<p><code>$item_tpl = '&lt;li&gt;&lt;a href="{PAGE}.html" id="menu-{PAGE}"&gt;{TITLE}&lt;/a&gt;&lt;/li&gt;';</code></p>
<p>The new code and demo:</p>
<ul>
<li><a href="http://www.w3clubs.com/w3clubs-examples/ragtime4/">Demo</a></li>
<li><a href="http://www.w3clubs.com/w3clubs-examples/ragtime4/ragtime4-htaccess.zip">Code download</a></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://php.w3clubs.com/php-tutorial/project-ragtime-dynamic-urls/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Useful array functions</title>
		<link>http://php.w3clubs.com/php-tutorial/useful-array-functions/</link>
		<comments>http://php.w3clubs.com/php-tutorial/useful-array-functions/#comments</comments>
		<pubDate>Sun, 10 Aug 2008 09:01:28 +0000</pubDate>
		<dc:creator>admin</dc:creator>
		
		<category><![CDATA[PHP Tutorial]]></category>

		<guid isPermaLink="false">http://php.w3clubs.com/?p=23</guid>
		<description><![CDATA[PHP has a lot of functions that deal with arrays, as you can see by visiting the array section of the PHP manual. Let's see a few examples of using some of the most common functions. Do not try to remember them all, this is more of an informational article to demonstrate some of the [...]]]></description>
			<content:encoded><![CDATA[<p>PHP has a lot of functions that deal with arrays, as you can see by visiting the <a href="http://php.net/array">array section of the PHP manual</a>. Let's see a few examples of using some of the most common functions. Do not try to remember them all, this is more of an informational article to demonstrate some of the possibilities. When the need arises, you could always visit the PHP manual and find the most appropriate function for your specific need.</p>
<h3>A simple array</h3>
<p>Let's start by defining a simple array and printing out its contents.</p>
<p>(All examples assume that the code is enclosed in "&lt;pre&gt;" tags)</p>
<pre>
$a = array(
  'one'   =&gt; 1,
  'three' =&gt; 3,
  'two'   =&gt; 2,
  'four'  =&gt; 4
);
// print the array
print_r($a);
</pre>
<p>The result is simply:</p>
<blockquote>
<pre>
Array
(
    [one] =&gt; 1
    [three] =&gt; 3
    [two] =&gt; 2
    [four] =&gt; 4
)
</pre>
</blockquote>
<h3>Checking for existence</h3>
<p>You can use the function <a href="http://php.net/isset">isset()</a> that checks whether a variable (or an array index) is defined.</p>
<pre>
// key exists
if (isset($a['one'])) {
    echo 'key "one" exists';
}
</pre>
<p>This will print:</p>
<blockquote><p>
key "one" exists
</p></blockquote>
<p>Using <a href="http://php.net/empty">empty()</a> you can check if the key exists (same as <code>isset()</code>) but also if the array value with this key is a non-null value, in other words if something else than <code>0, "", null</code> or <code>FALSE</code>,</p>
<pre>
// key exists and its value is not 0, "", null or FALSE
if (!empty($a['one'])) {
    echo 'key "one" exists and has a value';
}
</pre>
<p>In our example array, array element with key "one" exists and its value is "1", so it's a non-null value. The code above will print:</p>
<blockquote><p>
key "one" exists and has a value
</p></blockquote>
<p>The function <a href="http://php.net/in_array">in_array()</a> checks if a specified value exists in a given array. Let's check if the value 4 exists in the <code>$a</code> array:</p>
<pre>
// value exists
if (in_array(4, $a)) {
    echo '4 is a value in the array';
}
</pre>
<p>The value 4 exists, so the code will print:</p>
<blockquote><p>
4 is a value in the array
</p></blockquote>
<h3>Implode, explode</h3>
<p><a href="http://php.net/implode">implode()</a> and explode() are two very useful functions that turn an array into a string and vise versa. Let's see how.</p>
<p><code>implode()</code> takes an array and a string (called delimiter) and returns a new string that has all the elements of the array with the delimiter string between them. Let's use the pipe symbol <code>|</code> as a delimiter:</p>
<pre>
echo implode("|", $a);
</pre>
<p>The result is:</p>
<blockquote><p>
1|3|2|4
</p></blockquote>
<p>Now let's see the opposite - we have a string and want to produce an array out of it. In the string "here,there,everywhere" we can use the comma as a delimiter:</p>
<pre>
$str = 'here,there,everywhere';
$b = explode(",", $str);
print_r($b);
</pre>
<p>Using <code>explode()</code> will create an array where the first element is "here", the second is "there" and the third is "everywhere". So the result of the code above will be:</p>
<blockquote>
<pre>
Array
(
    [0] =&gt; here
    [1] =&gt; there
    [2] =&gt; everywhere
)
</pre>
</blockquote>
<h3>Keys, values, reverse</h3>
<p>Continuing with the useful array functions, let's see the functions <a href="http://php.net/array_keys">array_keys()</a>, <a href="http://php.net/array_values">array_values()</a> and <a href="http://php.net/array_reverse">array_reverse()</a>.</p>
<p><code>array_keys()</code> will take an array and return a new (enumerated) array, containing only the keys of the input array. <code>array_values()</code> will do the opposite - return a new array with the values only, so you'll lose the original keys. <code>array_reverse()</code> takes an array and reverses the order pf the elements, the last element becomes first and so on. It keeps the keys pointing to the same values.</p>
<pre>
// keys only
print_r(array_keys($a));
// value only
print_r(array_values($a));
// reverse the array
print_r(array_reverse($a));
</pre>
<p>The code above will print:</p>
<blockquote>
<pre>
Array
(
    [0] =&gt; one
    [1] =&gt; three
    [2] =&gt; two
    [3] =&gt; four
)
Array
(
    [0] =&gt; 1
    [1] =&gt; 3
    [2] =&gt; 2
    [3] =&gt; 4
)
Array
(
    [four] =&gt; 4
    [two] =&gt; 2
    [three] =&gt; 3
    [one] =&gt; 1
)
</pre>
</blockquote>
<h3>... and counting</h3>
<p>The <a href="http://php.net/count">count()</a> returns the number of elements in an array, useful when using <a href="/php-tutorial/for-loops"><code>for</code> loops</a> for example.</p>
<pre>
// count the elements
echo count($a); // prints 4
</pre>
<h3>Random stuff</h3>
<p><a href="http://php.net/shuffle">shuffle()</a> takes an array and randomizes its elements.</p>
<pre>
// shuffle
$b = array_keys($a);
shuffle($b);
print_r($b);
</pre>
<p>This will produce something like.</p>
<blockquote>
<pre>
Array
(
    [0] =&gt; four
    [1] =&gt; three
    [2] =&gt; one
    [3] =&gt; two
)
</pre>
</blockquote>
<p>Another way to get random elements from an array is to use the function <a href="http://php.net/array_rand">array_rand()</a></p>
<h3>Sorting</h3>
<p>There are quite a few functions that sort arrays - some sort ascending, some descending, some sort keys, some sort values, some keep the original keys of the array, some "re-key" the input array. There are also 3 functions that let you define custom sorting. </p>
<p>Let's see some of the built-in sorting functions.</p>
<p><a href="http://php.net/sort">sort()</a> orders the elements of the array in ascending order (smallest first) and re-keys the array.</p>
<pre>
// sort ascending
$b = $a;
sort($b);
print_r($b);
</pre>
<p>Note that we used a new value $b, this is because <code>sort()</code> will simply return a new modified array, but will actually change the input array, so we lose the original when we pass it to <code>sort()</code>. The code above prints:</p>
<blockquote>
<pre>
Array
(
    [0] =&gt; 1
    [1] =&gt; 2
    [2] =&gt; 3
    [3] =&gt; 4
)
</pre>
</blockquote>
<p><a href="http://php.net/rsort">rsort()</a> is like <code>sort()</code>, only it sorts the element in descending order. ("r" for "reversed")</p>
<pre>
// sort descending
$b = $a;
rsort($b);
print_r($b);
</pre>
<p>The code above prints:</p>
<blockquote>
<pre>
Array
(
    [0] =&gt; 4
    [1] =&gt; 3
    [2] =&gt; 2
    [3] =&gt; 1
)
</pre>
</blockquote>
<p>"k" stands for "key". So <a href="http://php.net/ksort">ksort()</a> is like <code>sort()</code> but it sorts keys of the array.</p>
<pre>
// sort keys
$b = $a;
ksort($b);
print_r($b);
</pre>
<blockquote>
<pre>
Array
(
    [four] =&gt; 4
    [one] =&gt; 1
    [three] =&gt; 3
    [two] =&gt; 2
)
</pre>
</blockquote>
<p>Since "k" is "key" and "r" is "reverse" what would be the function to sort the elements in descending order, ordered by key? Mhm, <a href="http://php.net/krsort">krsort()</a>.</p>
<h3>Summary</h3>
<p>So you get the idea, there are tons of array functions, some you'll use quite often so that you'll memorize their names and attributes. Other functions you'll use less often, but the PHP manual is always there for you to consult.</p>
]]></content:encoded>
			<wfw:commentRss>http://php.w3clubs.com/php-tutorial/useful-array-functions/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Accepting user input through GET</title>
		<link>http://php.w3clubs.com/php-tutorial/get-user-input/</link>
		<comments>http://php.w3clubs.com/php-tutorial/get-user-input/#comments</comments>
		<pubDate>Sun, 10 Aug 2008 09:00:46 +0000</pubDate>
		<dc:creator>admin</dc:creator>
		
		<category><![CDATA[PHP Tutorial]]></category>

		<guid isPermaLink="false">http://php.w3clubs.com/?p=22</guid>
		<description><![CDATA[Your smart PHP application should be able to accept user input and serve different pages, depending on the user request. This is really powerful, let's see how you can achieve it. 
There are different ways for a web page to accept input from the user, the most common being through GET and POST requests.
What's in [...]]]></description>
			<content:encoded><![CDATA[<p>Your smart PHP application should be able to accept user input and serve different pages, depending on the user request. This is really powerful, let's see how you can achieve it. </p>
<p>There are different ways for a web page to accept input from the user, the most common being through GET and POST requests.</p>
<h3>What's in a request</h3>
<p>When a user clicks on a link or types in the address bar, he/she requests a page (a file, a resource) from a remote server. This is done through the use of the HTTP protocol, so we say that the user makes an HTTP request. The resources out there are identifiable by their URL. </p>
<p>Let's take a URL:<br />
<code>http://www.w3clubs.com/w3clubs-examples/ragtime2/index.php</code></p>
<p>What we have here:</p>
<ul>
<li>The whole thing is a URL</li>
<li><code>http</code> identifies the protocol</li>
<li><code>www.w3clubs.com</code> is the host name</li>
<li><code>/w3clubs-examples/ragtime2/index.php</code> identifies where the resource is located</li>
</ul>
<p>Just for information, here's how an HTTP request may look like:</p>
<pre>
GET /w3clubs-examples/ragtime2/index.php HTTP/1.1
Host: www.w3clubs.com
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.7) Gecko/20070914 Firefox/2.0.0.7
Accept: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 300
Connection: keep-alive
Referer: http://www.w3clubs.com/w3clubs-examples/ragtime2/
Cache-Control: max-age=0
</pre>
<p>To see the HTTP headers being exchanged when you request and receive pages, I'd recommend using the Firefox extensions <a href="http://livehttpheaders.mozdev.org/">LiveHTTPHeaders</a> or the Net panel of <a href="http://www.getfirebug.com">Firebug</a>. For IE and other browsers on Windows you can also use <a href="http://www.fiddlertool.com/">Fiddler</a>.</p>
<h3>GET</h3>
<p>Notice the word GET in the request above? It specifies the request method. </p>
<p>Now let's check this URL:<br />
<code>http://www.w3clubs.com/w3clubs-examples/ragtime2/index.php?key=value</code></p>
<p>The part after the question mark is called a query string, it allows you to pass parameters when making a request. You can have several query parameters, divided by an <code>&amp;</code></p>
<p><code>http://www.w3clubs.com/w3clubs-examples/ragtime2/index.php?key=value&amp;something=else</code></p>
<p>The cool thing is that in your PHP script you have access to those parameters and can do different things, for example branch the page execution, based on different values being passed in the query string. </p>
<p>You can access the query string parameters (let's call them GET parameters) through the array <code>$_GET</code> which PHP defines for you. Let's see an example.</p>
<h3>Example</h3>
<p>Create the script <code>C:\mywebstuff\htdocs\php-tutorial\get.php</code> (how to setup <a href="/php-tutorial/installing-php">here</a>) with the following contents:</p>
<pre>
&lt;pre&gt;
&lt;?php
print_r($_GET);
?&gt;
&lt;/pre&gt;
</pre>
<p>Now load this script in the browser, like <code>http://localhost/php-tutorial/get.php</code></p>
<p>The result might be slightly disappointing, but it does illustrate something important - that the <code>$_GET</code> array is always defined. The result is:</p>
<blockquote><pre>
Array
(
)
</pre>
</blockquote>
<p>Now let's change the URL of the request to:<br />
<code>http://localhost/php-tutorial/get.php?key=value</code></p>
<p>The result:</p>
<blockquote><pre>
Array
(
    [key] =&gt; value
)
</pre>
</blockquote>
<p>And how about <code>http://localhost/php-tutorial/get.php?key=value&amp;something=else</code></p>
<blockquote><pre>Array
(
    [key] =&gt; value
    [something] =&gt; else
)</pre>
</blockquote>
<h3>Never trust user input</h3>
<p>You just learned how to get user input and now I'm telling you not to trust it. What gives?</p>
<p>Not trusting user input is an important lesson (that many have learned the hard way) and cannot be over-emphasized.</p>
<p>Let's say you have the following script:</p>
<pre>
&lt;?php
echo 'Hello ', $_GET['user'], '!';
?&gt;
</pre>
<p>When you request is like <code>http://localhost/php-tutorial/user.php?user=stoyan</code>, this is a friendly little page that greats me:</p>
<blockquote><p>
Hello stoyan!
</p></blockquote>
<p>But as a malicious user I can try adding HTML tags in my username and nothing in the script will stop me:<br />
<code>http://localhost/php-tutorial/user.php?user=&lt;b&gt;stoyan&lt;/b&gt;</code></p>
<p>This will result in:</p>
<blockquote><p>
Hello <b>stoyan</b>!
</p></blockquote>
<p>So what? So far, not so bad. But why stop here? I can also pass javascript as a parameter.<br />
<code>http://localhost/php-tutorial/user.php?user=&lt;script&gt;location='http://www.phpied.com'&lt;/script&gt;</code></p>
<p>What will happen? As soon as you load the page, you're redirected to my blog at <a href="http://www.phpied.com">http://www.phpied.com</a>, because the script printed whatever was passed as 'user' parameter, so the HTML looks like:</p>
<pre>Hello &lt;script&gt;location='http://phpied.com'&lt;/script!&gt;</pre>
<p>Redirecting to a page is bad enough, but could be worse. With javascript you have access to the browser cookies, so a malicious user can not only redirect to a new page, but also send your cookies to this page and this way steal your session. Imagine PayPal doing such a mistake. A hacker can get your session ID and put it in his browser cookies, this way logging in as you and making some payments. Scary stuff.</p>
<p>The take-home message here is:<br />
When you accept user input, expect the unexpected. If you ask for example for a phone number from the user, don't assume you'll only be receiving numbers, be also prepared to deal with all kinds of characters, HTML and JavaScript strings. </p>
<p>What's the fix to the vulnerability above? Surprisingly simple, just use function <a href="http://php.net/htmlspecialchars">htmlspecialchars()</a>, it will make all <code>&gt;</code> and <code>&lt;</code> into <code>&amp;gt;</code> and <code>&amp;lt;</code> and the script will never be executed.</p>
<pre>
&lt;?php
if (!empty($_GET['user'])) {
    echo 'Hello ', htmlspecialchars($_GET['user']), '!';
}
?&gt;
</pre>
<p>The result displayed in the browser will be:</p>
<blockquote><p>Hello &lt;script&gt;location='http://phpied.com'&lt;/script&gt;!</p></blockquote>
<p>because the HTML code generated will be:</p>
<pre>
Hello &amp;lt;script&amp;gt;location='http://phpied.com'&amp;lt;/script&amp;gt;!
</pre>
]]></content:encoded>
			<wfw:commentRss>http://php.w3clubs.com/php-tutorial/get-user-input/feed/</wfw:commentRss>
		</item>
		<item>
		<title>A few useful debugging functions</title>
		<link>http://php.w3clubs.com/php-tutorial/debuggin-functions/</link>
		<comments>http://php.w3clubs.com/php-tutorial/debuggin-functions/#comments</comments>
		<pubDate>Sun, 10 Aug 2008 08:59:36 +0000</pubDate>
		<dc:creator>admin</dc:creator>
		
		<category><![CDATA[PHP Tutorial]]></category>

		<guid isPermaLink="false">http://php.w3clubs.com/?p=21</guid>
		<description><![CDATA[So now that you know what's a PHP array and what's a PHP variable, let's see a few functions that can help you get a good idea what's the content of a variable at any time .
print_r()
print() is a language construct, almost the same as echo and can be used instead of echo to print [...]]]></description>
			<content:encoded><![CDATA[<p>So now that you know what's a <a href="/php-tutorial/arrays-part-1/">PHP array</a> and what's a <a href="/php-tutorial/variables/">PHP variable</a>, let's see a few functions that can help you get a good idea what's the content of a variable at any time .</p>
<h3>print_r()</h3>
<p><a href="http://php.net/print"><code>print()</code></a> is a language construct, almost the same as <code>echo</code> and can be used instead of <code>echo</code> to print strings. <a href="http://php.net/print_r"><code>print_r()</code></a> on the other hand is a function that prints a variable recursively, meaning that it can print all elements of an array, even if it consist of other arrays.</p>
<p>Let's see an example:</p>
<pre>
$a = array(1, 2, 3, array(4, 5, 6));
echo $a; // prints "Array", not useful at all
print $a; // same as above
echo '&lt;pre&gt;'
print_r($a); // the good stuff
echo '&lt;/pre&gt;'
</pre>
<p>So <code>echo</code> and <code>print</code> will output "Array", that's the best they can do, because they accept string input, not arrays. <code>print_r()</code> will output the array very nicely in a readable format, so that you know exactly what's the contents of the array. The output from the <code>print_r()</code> in the code above will be:</p>
<blockquote>
<pre>
Array
(
    [0] =&gt; 1
    [1] =&gt; 2
    [2] =&gt; 3
    [3] =&gt; Array
        (
            [0] =&gt; 4
            [1] =&gt; 5
            [2] =&gt; 6
        )

)
</pre>
</blockquote>
<p>Very useful when at some point in the development, you're no longer sure what exactly is in this array.</p>
<p>If you give a string or a number to <code>print_r()</code> instead of an array, it will act as a normal <code>print</code> call.</p>
<h3>var_dump()</h3>
<p>Similarly to <code>print_r()</code> you can get an idea of the contents of an array by using <a href="http://php.net/var_dump"><code>var_dump()</code></a>. In addition to what <code>print_r()</code> gives, it will also report the size of an array (or sub-array) and will report the type of each value.</p>
<p>An example use of <code>var_dump()</code>:</p>
<pre>
$a = array('one', true, 3.14, array(4, 5, 6));
echo '&lt;pre&gt;'
var_dump($a);
echo '&lt;/pre&gt;'
</pre>
<p>The result is:</p>
<blockquote><pre>
array(4) {
  [0]=&gt;
  string(3) "one"
  [1]=&gt;
  bool(true)
  [2]=&gt;
  float(3.14)
  [3]=&gt;
  array(3) {
    [0]=&gt;
    int(4)
    [1]=&gt;
    int(5)
    [2]=&gt;
    int(6)
  }
}
</pre>
</blockquote>
<p>Given scalar data (not an array), <code>var_dump()</code> will behave similarly.</p>
<pre>
var_dump('one'); // string(3) "one"
</pre>
<p>You can pass as many values or variables to <code>var_dump()</code> as you want.</p>
<pre>
var_dump('one', 'two', 3);
</pre>
<p>The above will print:</p>
<blockquote><pre>
string(3) "one"
string(3) "two"
int(3)
</pre>
</blockquote>
<h3>var_export()</h3>
<p><a href="http://php.net/var_export"><code>var_export()</code></a> is similar to <code>var_dump()</code> and <code>print_r()</code>, but with one significant difference - it produces valid PHP code. You can take the output and put it a PHP script as a normal PHP code.</p>
<pre>
$a = array('one', true, 3.14, array(4, 5, 6));
echo '&lt;pre&gt;'
var_export($a);
echo '&lt;/pre&gt;'
</pre>
<p>The result is:</p>
<blockquote><pre>
array (
  0 =&gt; 'one',
  1 =&gt; true,
  2 =&gt; 3.14,
  3 =&gt;
  array (
    0 =&gt; 4,
    1 =&gt; 5,
    2 =&gt; 6,
  ),
)
</pre>
</blockquote>
]]></content:encoded>
			<wfw:commentRss>http://php.w3clubs.com/php-tutorial/debuggin-functions/feed/</wfw:commentRss>
		</item>
		<item>
		<title>&#8220;foreach&#8221; loops</title>
		<link>http://php.w3clubs.com/php-tutorial/foreach-loops/</link>
		<comments>http://php.w3clubs.com/php-tutorial/foreach-loops/#comments</comments>
		<pubDate>Sun, 10 Aug 2008 08:55:40 +0000</pubDate>
		<dc:creator>admin</dc:creator>
		
		<category><![CDATA[PHP Tutorial]]></category>

		<guid isPermaLink="false">http://php.w3clubs.com/?p=20</guid>
		<description><![CDATA[You know about for loops, now let's see another kind - the foreach loop. It's used only to iterate over the elements of an array and cannot be used as a general-purpose iterator the way for can be.
Quick example

// define an array
$myarray = array('one', 'two', 'three');
// loop
foreach ($myarray as $tmp) {
    echo [...]]]></description>
			<content:encoded><![CDATA[<p>You know about <code><a href="/php-tutorial/for-loops/">for</a></code> loops, now let's see another kind - the <code><a href="http://php.net/foreach">foreach</a></code> loop. It's used only to iterate over the elements of an array and cannot be used as a general-purpose iterator the way <code>for</code> can be.</p>
<h3>Quick example</h3>
<pre>
// define an array
$myarray = array('one', 'two', 'three');
// loop
foreach ($myarray as $tmp) {
    echo $tmp, '&lt;br /&gt;';
}
</pre>
<p>This code will print:</p>
<blockquote><p>
one<br />
two<br />
three
</p></blockquote>
<p>Let's see what we've got here:</p>
<ul>
<li>First there's the construct <code>foreach</code> followed by something in brackets.</li>
<li>Then just like the <code>for</code> loop we have a block of code, enclosed in curly brackets. This code is executed on every iteration.</li>
<li>How many iterations there would be? As many as the elements in the array being looped.</li>
<li>In the parentheses after <code>foreach</code> we have the array followed by the construct "<code>as</code>", followed by another variable. On every iteration, the value of next element in the array will be assigned to the new variable.</li>
</ul>
<p>In the example above, at the first iteration <code>$tmp</code> will have the value "one", in the second iteration, the value of <code>$tmp</code> will be "two", the third iteration - "three". </p>
<p>Note that <code>$tmp</code> lives after the end of the loop. After the loop $tmp will still be defined and will have the value of the last array element, in this case "three".</p>
<h3>Access to the keys while looping</h3>
<p>OK, so in the example above we printed out the values of the array elements, but what about their keys?</p>
<p>To access the keys of an array while in a loop, you can use the following variant of the <code>foreach</code> construct:</p>
<pre>foreach($array as $key =&gt; $value) {...}</pre>
<p>On every iteration <code>$key</code> will contain the key of the next array element, and <code>$value</code> will hold the value.</p>
<p>Let's see the example above, slightly modified to print the keys.</p>
<pre>
// define an array
$myarray = array('one', 'two', 'three');
// loop using $k (as in "key") and $v as "value"
foreach ($myarray as $k =&gt; $v) {
    echo 'Key: ', $k, ', value: ', $v, '&lt;br /&gt;';
}
</pre>
<p>This code will print:</p>
<blockquote><p>
Key: 0, value: one<br />
Key: 1, value: two<br />
Key: 2, value: three
</p></blockquote>
<h3>Associative arrays example</h3>
<p>So far we only used enumerated arrays, but the associative arrays can be looped over the same way.</p>
<pre>
// define an array
$myarray = array(
    'name' =&gt; 'Hendrix',
    'first' =&gt; 'Jimi',
    'song' =&gt; 'Foxy Lady'
);
// loop using $k (as in "key") and $v as "value"
echo 'Now playing:';
foreach ($myarray as $k =&gt; $v) {
    echo $k, ': ', $v, '&lt;br /&gt;';
}
</pre>
<p>This will print:</p>
<blockquote><p>
Now playing:<br />
name: Hendrix<br />
first: Jimi<br />
song: Foxy Lady
</p></blockquote>
<h3>Updating the array while in the loop</h3>
<p>This code won't change anything in the array:</p>
<pre>
$myarray = array(1, 2, 3, 4, 5);
foreach($myarray as $k =&gt; $v) {
    $v = $v * 2;
}
</pre>
<p>This simply changes the <code>$v</code> variable, but not the value in the original array. To change the array, we can address its elements using the current key:</p>
<pre>
$myarray = array(1, 2, 3, 4, 5);
foreach($myarray as $k =&gt; $v) {
    $v = $v * 2;
    $myarray[$k] = $v;
}
</pre>
<p>After this code executes, you'll have an updated array that looks like this:</p>
<pre>array(2, 4, 6, 8, 10)</pre>
]]></content:encoded>
			<wfw:commentRss>http://php.w3clubs.com/php-tutorial/foreach-loops/feed/</wfw:commentRss>
		</item>
		<item>
		<title>&#8220;for&#8221; loops</title>
		<link>http://php.w3clubs.com/php-tutorial/for-loops/</link>
		<comments>http://php.w3clubs.com/php-tutorial/for-loops/#comments</comments>
		<pubDate>Sun, 10 Aug 2008 08:55:05 +0000</pubDate>
		<dc:creator>admin</dc:creator>
		
		<category><![CDATA[PHP Tutorial]]></category>

		<guid isPermaLink="false">http://php.w3clubs.com/?p=19</guid>
		<description><![CDATA[Sometimes you want to run an operation several times, or you want to go through all the elements of an array. How do you do that? Using loops.
Loop 10 times
Let's see a simple example of a loop.

for ($i = 0; $i &#60; 100; $i++) {
    echo "This punishment is not boring and [...]]]></description>
			<content:encoded><![CDATA[<p>Sometimes you want to run an operation several times, or you want to go through all the elements of <a href="/php-tutorial/arrays-part-1/">an array</a>. How do you do that? Using loops.</p>
<h3>Loop 10 times</h3>
<p>Let's see a simple example of a loop.</p>
<pre>
for ($i = 0; $i &lt; 100; $i++) {
    echo "This punishment is not boring and pointless.&lt;br /&gt;";
}
</pre>
<p>If you execute this, it will write down the sentence a hundred times. Let's see what the loop consists of.</p>
<ul>
<li>The part in curly brackets is the block of code to be executed at every iteration (every time the loop "ticks"). </li>
<li>The part after the word "for" in the brackets is setting up the loop properties. It consists of three expressions, divided by semi-colons.
<ol>
<li><code>$i = 0;</code> - this part is initializing the loop, here you can set up some variables. This part is always executed. Usually it's used to set a "counter" variable, by convention named <code>$i</code></li>
<li><code>$i &lt; 100</code> - this part is a condition (similar to an if-else condition) that has to evaluate to TRUE, otherwise the loop stops. This is the place where usually you define the boundary condition, after which the loops is no longer executing. In the case above, we set that after 100 repetitions, the loop should exit</li>
<li><code>$i++</code> - this part is executed at the end of every iteration. Often it simply increments the $i counter variable</li>
</ol>
</li>
</ul>
<h3>More examples</h3>
<p>Let's print the numbers from 1 to 10, using the <code>$i</code> counter variable that we increment on every iteration.</p>
<pre>
for ($i = 1; $i &lt;= 10; $i++) {
    echo $i, '&lt;br /&gt;';
}
</pre>
<p>You can use several statements in the expressions divided by semi-colons. Let's see two ways of printing the numbers from 1 to 10 ascending and descending.</p>
<pre>
$k = 10;
for ($i = 1; $i &lt;= 10; $i++) {
    echo $i, ' -- ', ($k - $i +1), '&lt;br /&gt;';
}
</pre>
<p>This will print something like:</p>
<blockquote><p>
1 -- 10 // $i is 1, so 10 - 1 + 1 is 10<br />
2 -- 9  // $i is 2 and 10 - 2 + 1 is 9<br />
3 -- 8<br />
4 -- 7<br />
5 -- 6<br />
6 -- 5<br />
7 -- 4<br />
8 -- 3<br />
9 -- 2<br />
10 -- 1 // $i is 10 so 10 - 10 + 1 is 1
</p></blockquote>
<p>The same can be achieved by moving the initialization of <code>$k</code> inside the initialization part of the loop and moving the little calculation we had in the third expression of the loop, together with <code>$i++</code>. The calculation can actually be a simple decrement. This keeps the block of code simpler.</p>
<pre>
for ($i = 1, $k = 10; $i &lt;= 10; $i++, $k--) {
    echo $i, ' -- ', $k, '&lt;br /&gt;';
}
</pre>
<p>As you can see, when you need to do two or more things inside a <code>for</code> expression, you use comma as a separator.</p>
<h3>Skipping an iteration</h3>
<p>You can use <code>continue</code> to skip a step. When you use it, the rest of the code in the block is not executed. Usually you use <code>continue</code> conditionally. The following prints only even numbers.</p>
<pre>
for ($i = 1; $i &lt;= 10; $i++) {
    if ($i % 2 != 0) {
        continue;
    }
    echo $i, '&lt;br /&gt;';
}
</pre>
<p>In this example we tested <code>$i</code> in every loop iteration and if we discover it's not an even number, we skip the rest.</p>
<p>BTW, the same can be done easier, but the aim was to see how <code>continue;</code> works. Here's the easier solution, it shows that the increment expression doesn't necessarily need to increment only by one.</p>
<pre>
for ($i = 2; $i &lt;= 10; $i += 2) {
    echo $i, '&lt;br /&gt;';
}
</pre>
<h3>Breaking out of the loop</h3>
<p>You can use <code>break;</code> inside the body of the loop to exit at any time. Usually the break is also conditional.</p>
<pre>
//  loop ends when $i is 100
for ($i = 2; $i &lt;= 100; $i += 2) {
    echo $i, '&lt;br /&gt;';
    if ($i == 10) {
        // exit prematurely when $i is 10
        break;
    }
}
</pre>
<p>The result of executing this code is printing only the numbers 2, 4, 6, 8, 10.</p>
<h3>Nested loops</h3>
<p>You can nest loops within each other. The following example prints the multiplication table from 1 to 10.</p>
<pre>
&lt;?php
for($i = 1; $i &lt;= 10; $i++){
    echo '&lt;h2&gt;Multiplication by ', $i, '&lt;/h2&gt;';
    for($j = 1; $j &lt;= 10; $j++) {
        echo $i, ' * ', $j, ' = ', ($i*$j);
        echo '&lt;br /&gt;';
    }
}
?&gt;
</pre>
<p>Here's a <a href="http://www.w3clubs.com/w3clubs-examples/php/multitable.php">demo of this script in action</a>.</p>
<h3>Looping through an array</h3>
<p>Let's say we have the array <code>$a = array(1, 3, 5, 7, 9);</code>. Let's print all the elements.</p>
<p>First we need to know when the loops should end. We figure that out using the <code><a href="http://php.net/count">count()</a></code> function which returns the number of elements in the array. Another important thing to remember is that array keys start from 0, so you loop from 0 to the number of elements minus 1.</p>
<pre>
$max = count($a);
for($i = 0; $i &lt; $max; $i++) {
    echo $a[$i], '&lt;br /&gt;';
}
</pre>
<p>This code will print all the elements of the <code>$a</code> array.</p>
]]></content:encoded>
			<wfw:commentRss>http://php.w3clubs.com/php-tutorial/for-loops/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Arrays - part 2</title>
		<link>http://php.w3clubs.com/php-tutorial/arrays-part-2/</link>
		<comments>http://php.w3clubs.com/php-tutorial/arrays-part-2/#comments</comments>
		<pubDate>Sun, 10 Aug 2008 08:53:43 +0000</pubDate>
		<dc:creator>admin</dc:creator>
		
		<category><![CDATA[PHP Tutorial]]></category>

		<guid isPermaLink="false">http://php.w3clubs.com/?p=18</guid>
		<description><![CDATA[Let's continue the journey into the wonderful world of the PHP arrays, the first part of the trip is located here.
Associative arrays
Associative arrays are different than the enumerated arrays in the fact that their keys are more flexible, they can be strings, not only numbers. So you can think of the associative arrays (also called [...]]]></description>
			<content:encoded><![CDATA[<p>Let's continue the journey into the wonderful world of the PHP arrays, <a href="/php-tutorial/arrays-part-1">the first part of the trip is located here</a>.</p>
<h3>Associative arrays</h3>
<p>Associative arrays are different than the enumerated arrays in the fact that their keys are more flexible, they can be strings, not only numbers. So you can think of the associative arrays (also called hash arrays) as tables that have a column for keys and a column for the corresponding values. If you want to access the value of an array element, you address it by its key, just like with the enumerated arrays.</p>
<table>
<caption>A table of keys and values</caption>
<tbody>
<tr>
<th>Key</th>
<th>Value</th>
</tr>
<tr>
<td>name</td>
<td>Man</td>
</tr>
<tr>
<td>first_name</td>
<td>Super</td>
</tr>
<tr>
<td>occupation</td>
<td>Superhero</td>
</tr>
</tbody>
</table>
<p>The following code represents this table as a PHP associative array:</p>
<pre>
$dude = array(
    'name' =&gt; 'Man',
    'first_name' =&gt; 'Super',
    'occupation' =&gt; 'Superhero'
);
</pre>
<p>As you see in the example, the keys and the values are divided by the <code>=&gt;</code> symbol. The keys are enclosed in quotes.</p>
<p>If you want to use this array to print a sentence, you can do something like:</p>
<pre>
// prints "SuperMan is a superhero"
echo $dude['first_name'], $dude['man'], ' is a ', $dude['occupation'];
</pre>
<h3>Case sensitive keys</h3>
<p>Array keys are case sensitive and also allow spaces and numbers, so these are all valid keys:</p>
<pre>
$arr = array(
    'FirstName' =&gt; 'Super',
    'firstname' =&gt; 'Duper',
    'First name' =&gt; 'Ultra',
    '1st name' =&gt; 'Mega',
);
</pre>
<h3>Adding to an array</h3>
<p>You can add to an array at any time, just by specifying the key in square brackets.</p>
<pre>
// define an empty array
$ar = array();

// add some elements
$ar['name'] = 'Superman';
$ar['powers'] = 'Super';
</pre>
<p>Note that in this case you use the normal assignment operator (<code>=</code>), not the <code>=&gt;</code> one.</p>
<h3>Modifying elements</h3>
<p>Modifying an element has exactly the same syntax as adding.</p>
<pre>
// define an empty array
$ar = array();

// add an element
$ar['name'] = 'Superman';

// update the 'name' element
$ar['name'] = 'Batman';
</pre>
<h3>Removing any element</h3>
<p>Similarly to the enumerated arrays, you use the <code><a href="http://php.net/unset">unset()</a></code> function to delete an element.</p>
<pre>
$ar = array('one' =&gt; 1, 'two' =&gt; 2);
unset($ar['two']);
echo $ar['one']; // prints 1
echo $ar['two']; // prints nothing, a notice when E_ALL
</pre>
<h3>Mixing associative and enumerated arrays</h3>
<p>The two types of arrays are quite similar, actually both are defined using <code><a href="http://php.net/array">array()</a></code>, so there's no explicit way to say "I want an associative array". It all depends on the keys you use (or don't use). </p>
<ul>
<li>If you don't specify any keys, you're creating an enumerated array and the keys are set behind the scenes to auto-incrementing integers.</li>
<li>If you specify numeric keys, even if you use quotes, you're creating enumerated arrays.</li>
<li>If you specify string keys, you're creating an associative arrays.</li>
</ul>
<p>On top of that, both array types can be mixed, the result is an associative array with some enumerated behavior when you add to it. This is rarely useful, but still possible.</p>
<pre>
// define an empty array
$a = array();

// set key 1
$a['1'] = 1;

// set key 2
// the previous line created a numeric index 1
// so the next available auto-increment is 2
$a[] = 2;

// adding an associative key
$a['three'] = 3;

// again a numeric index
// the last numeric key was 2 so the new key will be 3
$a[] = 4;

// associative key using the empty string as a key
$a[''] = 'empty';

// skipping some numbers and setting key number 100
$a[100] = 100;

// the last numeric key was 100
// so the next key is 101 if we don't set it ourselves
$a[] = 101;

// you can use variables as keys
$next_key = 'some_key';
$a[$next_key] = 'Some value';
</pre>
<h3>Forgetting the quotes</h3>
<p>What if you create an associative array but you forget the quotes when you specify keys? Well, a string in the code that doesn't look like a variable or function or a quoted string is most likely <a href="/php-tutorial/constants/">a constant</a>. And if you use an undefined constant, its assumed value is the name of the constant. In the following example <code>$arr1</code> and <code>$arr2</code> end up being the same. With the difference that <code>$arr1</code> will throw a Notice if you have error reporting set to <code>E_ALL</code>.</p>
<pre>
$arr1 = array(
    mykey =&gt; 'my value',
);
$arr2 = array(
    'mykey' =&gt; 'my value',
);
</pre>
<p>As you <a href="/php-tutorial/errors-and-mishaps/">know already</a>, you should aim at writing code that doesn't throw any notices, so the take-home message here is "Don't forget the quotes".</p>
]]></content:encoded>
			<wfw:commentRss>http://php.w3clubs.com/php-tutorial/arrays-part-2/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Arrays - part 1</title>
		<link>http://php.w3clubs.com/php-tutorial/arrays-part-1/</link>
		<comments>http://php.w3clubs.com/php-tutorial/arrays-part-1/#comments</comments>
		<pubDate>Sun, 10 Aug 2008 08:53:14 +0000</pubDate>
		<dc:creator>admin</dc:creator>
		
		<category><![CDATA[PHP Tutorial]]></category>

		<guid isPermaLink="false">http://php.w3clubs.com/?p=17</guid>
		<description><![CDATA[In addition to the strings, numbers and booleans, there is another data type - the array. Arrays are really useful and powerful so it's a good idea to learn them well.
Enumerated lists
An array is a list of values. The values in the list can be of any type, including other arrays. Here's one array - [...]]]></description>
			<content:encoded><![CDATA[<p>In addition to the strings, numbers and booleans, there is another data type - the array. Arrays are really useful and powerful so it's a good idea to learn them well.</p>
<h3>Enumerated lists</h3>
<p>An array is a list of values. The values in the list can be of any type, including other arrays. Here's one array - it's a list of odd numbers.</p>
<pre>$myarray = array(1, 3, 5, 7, 9);</pre>
<p>As you can see, in order to define an array, you use the language construct <code>array()</code>, which looks just like a normal function. Elements inside an array are separated by commas.</p>
<p>In order to access an individual element of the array, you use square brackets and in the brackets you specify the position of the element you want, starting from zero.</p>
<pre>
echo $myarray[0]; // prints 1, the first element
echo $myarray[1]; // prints 3, the second element
echo $myarray[4]; // prints 9, the fifth (4 + 1) element
</pre>
<p>The elements of the list are identifiable by their key, this is the number you put in square brackets. The keys are automatically created starting from zero and incrementing. The first element has key 0, the second has key 1 and so on. Let's see a little table that illustrates the array we used above.</p>
<table>
<tr>
<th>Key</th>
<th>Value</th>
<th>Access using</th>
</tr>
<tr>
<td>0</td>
<td>1</td>
<td>$myarray[0]</td>
</tr>
<tr>
<td>1</td>
<td>3</td>
<td>$myarray[1]</td>
</tr>
<tr>
<td>2</td>
<td>5</td>
<td>$myarray[2]</td>
</tr>
<tr>
<td>3</td>
<td>7</td>
<td>$myarray[3]</td>
</tr>
<tr>
<td>4</td>
<td>9</td>
<td>$myarray[4]</td>
</tr>
</table>
<h3>Adding an element to an array</h3>
<p>To add a new element at the end of the array, just use square brackets without a value, like so:</p>
<pre>
// array with three elements
$a = array(1, 2, 3);
// adding a fourth element
$a[] = 4;
// adding one more element
$a[] = 5;
echo $a[4]; // prints the fifth element, value 5
</pre>
<p>Instead of using empty brackets, you can also specify an exact index when you add to an array, or modify an element.</p>
<pre>
// array with three elements
$a = array(1, 2, 3);
// adding a fourth element
$a[3] = 4;
// adding the hundredth element
$a[99] = 100;
</pre>
<p>It's not an error to skip indexes, but maybe not very practical most of the times. </p>
<p>If you attempt to use an element with a non-existing key, you'll get a <a href="/php-tutorial/errors-and-mishaps/">PHP notice</a> that this key doesn't exist. </p>
<pre>
// array with three elements
$a = array(1, 2, 3);
echo $a[88]; // throws a notice
</pre>
<h3>Removing elements</h3>
<p>You can remove elements from an array, using the <code><a href="http://php.net/unset">unset()</a></code> function. </p>
<pre>
// array with three elements
$a = array(1, 2, 3);
unset($a[1]); // remove the second element
echo $a[0]; // prints 1
echo $a[1]; // Notice: undefined offset,
            // meaning that this element doesn't exist
echo $a[2]; // prints 3
</pre>
<p>BTW, the <code>unset()</code> function can also be used to unset variables, as if they were never defined.</p>
<pre>
$a = 1;
echo $a; // prints 1
unset($a);
echo $a; // Notice: undefined variable $a
</pre>
<h3>Mixed values</h3>
<p>In the examples above we only stored integers in the arrays, but you can store any type of data.</p>
<pre>
$a = 1;
$b = "b";
$myarray = array(
  $a,
  $b,
  99.99,
  "Ninja!",
  array(11, 22, array(9, 8, 7));
);
// let's print!
echo $myarray[0]; // prints 1
echo $myarray[1]; // prints b
echo $myarray[2]; // prints 99.99
echo $myarray[3]; // prints Ninja!
echo $myarray[4][0]; // prints 11
echo $myarray[4][1]; // prints 22
echo $myarray[4][2][0]; // prints 9
echo $myarray[4][2][1]; // prints 8
echo $myarray[4][2][2]; // prints 7
</pre>
<p>Using two pairs of square brackets <code>[][]</code> you can access arrays contained within arrays. This way you can nest arrays as deep as you need.</p>
<p>Here's for example an array structure that contains a 3 by 3 grid of a tic-tac-toe game;</p>
<pre>
$ttt = array(
  array('x', 'x', 'o'),
  array('o', 'x', 'o'),
  array('x', 'o', 'x'),
);
// getting the cell in the middle
echo  $ttt[1][1]; // prints x
</pre>
<p>Note on syntax - it's OK to have a trailing comma after the last element, it's not an error (as long as it's only one comma).</p>
<pre>
$a = array(1, 2, 3); // this is OK
$a = array(1, 2, 3,); // this is OK
$a = array(1, 2, 3,,); // parse error
</pre>
<h3>Summary</h3>
<ol>
<li>Arrays are important, you'll see much more examples of their use in the following articles.</li>
<li>An array is a list of values, values are indexed by keys</li>
<li>You can store anything in an array, including other arrays</li>
</ol>
]]></content:encoded>
			<wfw:commentRss>http://php.w3clubs.com/php-tutorial/arrays-part-1/feed/</wfw:commentRss>
		</item>
		<item>
		<title>If-else conditions</title>
		<link>http://php.w3clubs.com/php-tutorial/if-else-conditions/</link>
		<comments>http://php.w3clubs.com/php-tutorial/if-else-conditions/#comments</comments>
		<pubDate>Sun, 10 Aug 2008 08:52:18 +0000</pubDate>
		<dc:creator>admin</dc:creator>
		
		<category><![CDATA[PHP Tutorial]]></category>

		<guid isPermaLink="false">http://php.w3clubs.com/?p=16</guid>
		<description><![CDATA[Here's an important construct in any programming language - the ability to branch program execution based on a result of a condition (a check). 
What if?
Think about this expression - If I reach the train station before 8:30 I'll catch the train, otherwise I'll have to wait for the next one. In some sort of [...]]]></description>
			<content:encoded><![CDATA[<p>Here's an important construct in any programming language - the ability to branch program execution based on a result of a condition (a check). </p>
<h3>What if?</h3>
<p>Think about this expression - If I reach the train station before 8:30 I'll catch the train, otherwise I'll have to wait for the next one. In some sort of programspeak pseudo-language this will look like: </p>
<pre>
if time less than 8:30
  catch the train
else
  wait the next one
endif
</pre>
<p>The "time less than 8:30" part is called a condition. A condition returns a boolean value - either <code>TRUE</code> or <code>FALSE</code>. If it returns <code>TRUE</code>, the next statement "catch the train" is executed. If the condition returns (evaluates to) <code>FALSE</code>, the <code>else</code> part ("wait for the next one") is executed.</p>
<h3>A PHP example</h3>
<p>Let's see an example with real PHP code.</p>
<pre>
$a = 5;
if ($a &gt; 1) {
    echo 'a is positive';
} else {
    echo 'a is negative or 0';
}
</pre>
<p>The syntax is that the condition is placed in brackets and the statements are in curly brackets.</p>
<h3>Comparison operators</h3>
<p>We already <a href="/php-tutorial/php-operators/">discussed some operators</a>, but not all. Let's introduce some more, the so-called conditional operators.</p>
<ul>
<li><code>$a == $b</code> returns TRUE if $a and $b are equal</li>
<li><code>$a === $b</code> returns TRUE if $a and $b are equal and are of the same type. For example if we have $a = 1 (integer) and $b = "1" (string), then $a == $b will return TRUE, but $a === $b will return FALSE</li>
<li><code>$a != $b</code> returns TRUE if $a and $b are NOT equal</li>
<li><code>$a !== $b</code> returns TRUE if $a and $b are NOT equal or not of the same type. Again if we have $a = 1 (integer) and $b = "1" (string), then $a != $b will return FALSE, but $a !== $b will return TRUE. Yes, think about it for a minute.</li>
<li><code>$a &gt; $b</code> returns TRUE if $a is greater than $b</li>
<li><code>$a &lt; $b</code> returns TRUE if $a is less than $b</li>
<li><code>$a &gt;= $b</code> returns TRUE if $a is greater than or equal to $b</li>
<li><code>$a &lt;= $b</code> returns TRUE if $a is less than or equal to $b</li>
<li><code>$a  $b</code> returns TRUE if $a is either greater or less than $b, or in other words $a and $b are NOT equal (same as <code>!=</code>, rarely seen in practice)</li>
</ul>
<p>The <code>==</code> operator is easily confused with the simple assignment <code>=</code>. When you use assignment in an if-condition, it's not an error, and in most cases you'll get the condition evaluated to TRUE, simply because the assignment was successful. For example:</p>
<pre>
$a = 5;
if ($a = 1) {
    echo $a;
} else {
    echo "A is not 1";
}
</pre>
<p>This code will print "1", because in the condition part instead of using == to check if $a is 1, we used assignment and gave $a the value 1. If we use comparison operator, the result will be "A is not 1".</p>
<pre>
$a = 5;
if ($a == 1) {
    echo $a;
} else {
    echo "A is not 1";
}
</pre>
<h3>The block</h3>
<p>The code enclosed in curly brackets <code>{</code> and <code>}</code> is called a block. It's an important concept in PHP (also in C, Java). We'll see more use of the blocks further on, for example in functions and loops. </p>
<p>One note on syntax - when you have an <code>if</code> codition and a block is only one line, the brackets are optional. So this is valid:</p>
<pre>
$a = 123;

// checking a
if ($a == 3)
  echo 'A is three';

// moving on
$a = 321;
</pre>
<p>A good practice is to use the brackets, even if they are not needed. This makes it easier to understand the code, no need to think about it. Also makes a bit easier to come to the code later and add a second line of code, in this case the brackets are required and they would already be there.</p>
<h3>Conditions</h3>
<p>Sometimes a simple check like  <code>$a == $b</code> is all you need, but other times you'll need a more specific set of checks. It's OK to have as many checks as you want in a single condition.</p>
<pre>
if ($a &gt; 10 &amp;&amp; $a &lt; 100) {
    echo "A is between 10 and 100";
}
</pre>
<p><code>&amp;&amp;</code> means AND. Its opposite is <code>||</code> which means OR. So the condition above can be read as "if a is greater than 10 and less than 100". </p>
<p>Here's another example, it can be read "if a is equal to 10 or to 100"</p>
<pre>
if ($a == 10 || $a == 100) {
    echo "A is either 10 or 100";
}
</pre>
<p>If you use <code>||</code> and at least one of the sub-conditions is TRUE, then the whole thing is TRUE. With <code>&amp;&amp;</code> it's the other way around - all individual sub-conditions have to be TRUE, otherwise the whole condition is FALSE. This has a performance impact, because PHP is smart enough to give up if at some point during the evaluation of the separate sub-conditions, the end result becomes clear. For example:</p>
<pre>
$a = 1;
if ($a == 5 &amp;&amp; $a &gt; 10 &amp;&amp; $a &lt; 1) {
    // some code
}
</pre>
<p>In this case after the first check <code>$a == 5</code> evaluates to FALSE, it becomes clear that the whole condition has no chance of being TRUE, so PHP will not execute all the following checks.</p>
<p>The performance lesson here is - put the most likely sub-conditions first, this might save some processing.</p>
<p>You can also mix <code>&amp;&amp;</code> and <code>||</code> in the same condition. If you find yourself writing a longer condition consisting of sub-conditions, use brackets to make the code easier to follow.</p>
<pre>
// hard to understand
if ($a == 5 &amp;&amp; $b == 5 || $a == 10 &amp;&amp; $b == 10) {}
// much better
if (($a == 5 &amp;&amp; $b == 5) || ($a == 10 &amp;&amp; $b == 10)) {}
</pre>
<h3>else and elseif</h3>
<p>As you see in some of the examples above, the <code>else</code> clause is not required, it's optional. </p>
<p>There is also <code>elseif</code> which you can use for a better execution control.</p>
<pre>
if ($a == 1) {
  echo 'A is 1';
} elseif ($a == 2) {
  echo 'A is 2';
} else if ($a == 3) {
  echo 'A is 3';
} else {
  echo 'I give up';
}
</pre>
<p>Both <code>elseif</code> and <code>else if</code> are OK.</p>
<h3>Truthy and falsy</h3>
<p>You can use conditions like <code>if ($a) {...}</code>. The result of the condition will depend on the value in $a. Most of the values are "truthy" and the condition will evaluate to TRUE, except the following which are all "falsy":</p>
<ul>
<li><code>""</code> (empty string). Note that a string with even a single space is truthy.</li>
<li><code>FALSE</code></li>
<li><code>NULL</code></li>
<li><code>0</code></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://php.w3clubs.com/php-tutorial/if-else-conditions/feed/</wfw:commentRss>
		</item>
	</channel>
</rss>
