<?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>Webcodez - The database of web programming tutorials &#187; for loop</title>
	<atom:link href="http://www.webcodez.net/tag/for-loop/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.webcodez.net</link>
	<description>Archive of tutorials on php,mysql,Javascript,html,css and other coding languages as well as code-snippets.</description>
	<lastBuildDate>Tue, 18 May 2010 16:43:49 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Basic Shopping Cart System</title>
		<link>http://www.webcodez.net/php-mysql/basic-shopping-cart-system/</link>
		<comments>http://www.webcodez.net/php-mysql/basic-shopping-cart-system/#comments</comments>
		<pubDate>Sat, 23 Jan 2010 10:50:20 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[PHP & MySql]]></category>
		<category><![CDATA[arrays]]></category>
		<category><![CDATA[for loop]]></category>
		<category><![CDATA[foreach loop]]></category>
		<category><![CDATA[GET]]></category>
		<category><![CDATA[net script]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[POST]]></category>
		<category><![CDATA[Shopping Cart System]]></category>
		<category><![CDATA[variables]]></category>

		<guid isPermaLink="false">http://www.webcodez.net/?p=192</guid>
		<description><![CDATA[NOTE: This is a tutorial on creating a basic shopping cart system and giving an idea on how to create the basic functions of a shopping cart system and does not explain the securing of user input or checking whether the added products &#8216;exist&#8217; as that all depend on what products you offer and so [...]]]></description>
			<content:encoded><![CDATA[<p><strong>NOTE:</strong> This is a tutorial on creating a basic shopping cart system and giving an idea on how to create the basic functions of a shopping cart system and does not explain the securing of user input or checking whether the added products &#8216;exist&#8217; as that all depend on what products you offer and so database interactions which are not used in the basic shopping cart system yet as they only explain the basic functions to handle it. Therefore another tutorial will be created for creating an advanced total shopping cart system, as soon as possible.</p>
<h3>Tutorial Content</h3>
<p>First off, this tutorial is meant for creating a very basic shopping cart system. Not offering a copy-pastable setup script. It will show you how you can create the following functions for your shopping cart system:</p>
<p>* Adding products ( stored into session arrays )</p>
<p>* Removing products</p>
<p>* Empty/Clear shopping cart</p>
<p>* Retrieving all products ( from session )</p>
<p>* Changing amount on products</p>
<p>We&#8217;ll just be creating a simple basic shopping cart system now that is cappable of these 4 things. We won&#8217;t be using classes, OOP yet, which we&#8217;ll be doing in the next tutorial ( Advanced Shopping Cart System ). Having mentioned this all &#8211; let&#8217;s start.</p>
<h3>Shopping Cart System File</h3>
<p><strong>Shpping Cart System PHP File and the structure of the session array containing all products of the shopping cart</strong></p>
<p>What I usually start off with is creating the files we&#8217;ll be using. Which is only one:</p>
<p>* cart.php</p>
<p>As sessions are an important part of this system we&#8217;ll obviously need to set session_start first to be able to use session variables.</p>
<p><strong>File: cart.php</strong></p>
<pre name="code" class="php:nogutter">&lt;?php
session_start();

?&gt;</pre>
<p>We&#8217;ll be using the session $_SESSON['sc'] to store all products into (sc = shoppingcart ). So if it isn&#8217;t there yet, we&#8217;ll make it an empty array:</p>
<pre name="code" class="php:nogutter">&lt;?php
session_start();

if(!isset($_SESSION['sc']))
   $_SESSION['sc'] = array();
?&gt;
</pre>
<p>isset is a function used to check if the variable or array has been set/defined. We put a ! before it to check if it has NOT been set yet. The array will be of the following structure (2 products for example, first product gets index 0 ( [0] ), second index 1, etc. ):</p>
<pre name="code" class="php:nogutter">$_SESSION['sc'] = array(
         [0] =&gt; array("ID" =&gt; product_id, "amount" =&gt; product_amount),
         [1] =&gt; array("ID" =&gt; product_id, "amount" =&gt; product_amount),
         ... etc ... );
</pre>
<p>So for each new product, an array is added to the array &#8217;sc&#8217;, containing the product ID and amount in cart. So for example to add a test product to the shopping cart at start:</p>
<pre name="code" class="php:nogutter">&lt;php
 session_start();

if(!isset($_SESSION['sc']))
   $_SESSION['sc'] = array();

//add test product if not already exists
if(!$_SESSION['sc'][0])
$_SESSION['sc'][0] = array("ID" =&gt; 1, "amount" =&gt; 10);
?&gt;
</pre>
<p>Now we added a test product, ID of the product is 1 and the amount we set to 10.</p>
<h3>Retrieve Current Products</h3>
<p><strong>Retrieve the products that are currently inside the shopping cart</strong></p>
<p>With this info we can already make it retrieve the current products in the shopping cart. We&#8217;ll do this using a foreach loop. First however, we&#8217;ll need to check if there are any products in it at all, otherwise say it&#8217;s empty. We use the function count to count the amount of sub-variables or sub-arrays in this case, for the array $_SESSION['sc']. As each sub-array represents a product, we can tell if there are any products by counting them using the count function. We&#8217;ll store that in a variable $products. If it&#8217;s a value greater than 0 ( if there are any sub-arrays/products ), retrieve the products:</p>
<pre name="code" class="php:nogutter">$products = count($_SESSION['sc']);
if($products &gt; 0) { //if there are more than 0 products in the shopping cart

    //... retrieve products ...

}else{

   echo "Empty";

}
</pre>
<p>We&#8217;re now going to use 2 loops to retrieve the products. The first loop is a for loop which we use to get all products ( which are all sub-arrays ).</p>
<pre name="code" class="php:nogutter">for($curr=0;$curr&lt;$products;$curr++) {

}
</pre>
<p>What the for loop basicly does here is set a variable $curr to 0 ( the first index -&gt; first product of the array ), which represents the product $_SESSION['sc'][0]. Then it executes the loop ( nothing yet inside ) for that product ( which is $_SESSION['sc'][0] in the first loop execution time, but which is always = $_SESSION['sc'][$curr] ). After executing the loop for that product, it checks whether there are any other products by checking if $curr ( the current index ) is smaller than the amount of products. Which is equal to the last index + 1, as the first product starts with the index 0 instead of 1, and counting products start by 1 of course. So if there are any more products, it gets the next one which has the next array index. As the previous index = $curr, the next one is $curr++, which increases the current index by 1.</p>
<p>Ok so now we can handle all products inside this loop. The current product will be $_SESSION['sc'][$curr] as $curr contains the index of the current product. But as each array got it&#8217;s own sub-array (containing the ID and Amount) we need to use a forloop. This will get both the ID and Amount values of the products (sub-arrays):</p>
<pre name="code" class="php:nogutter">for($curr=0;$curr&lt;$products;$curr++) {

    foreach( $_SESSION['sc'][$curr] as $key =&gt; $value ) {

        echo $key.":".$value." &lt;br /&gt;";

    }

}
</pre>
<p>We know each product has it&#8217;s own index ( $curr ) and as value a sub-array like this:</p>
<blockquote><p>array(&#8220;ID&#8221; =&gt; prod_id, &#8220;amount&#8221; =&gt; prod_amount)</p></blockquote>
<p>So what we do is use a foreach loop to get the indexes ( ID and Amount ) of the array/product and the values of them (product id and product amount ). Then we echo them like this:</p>
<pre name="code" class="php:nogutter">        echo $key.":".$value." &lt;br /&gt;";
</pre>
<p>which outputs:</p>
<blockquote><p>ID: product id here<br />
amount: product amount here</p></blockquote>
<p>for each product it found in the for loop.</p>
<p>Let&#8217;s put this all together:</p>
<pre name="code" class="php:nogutter">&lt;php
  session_start();

 if(!isset($_SESSION['sc']))
    $_SESSION['sc'] = array();

//removed test product

$products = count($_SESSION['sc']);
if($products &gt; 0) { //if there are more than 0 products in the shopping cart

   for($curr=0;$curr&lt;$products;$curr++) {

    foreach( $_SESSION['sc'][$curr] as $key =&gt; $value ) {

         echo $key.":".$value." &lt;br /&gt;";

     }
   }

}else{

   echo "Empty";

}
</pre>
<p>Now we completed the first function for our shopping cart system: Retrieving all products. 4 more to go!</p>
<h3>Function &#8211; Add Products</h3>
<p><strong>Function to add products to the shopping cart</strong></p>
<p>Let&#8217;s start with creating a function to add a product. This shouldn&#8217;t be such a big hassle having discusses all of the structure of the shopping cart array and product sub-arrays. What we basicly need to do is add a new sub-array with the index of the last product&#8217;s index + 1 and create the sub array with the product ID and amount. We&#8217;ll have a look at the code:</p>
<pre name="code" class="php:nogutter">    $new = count($_SESSION['sc']);
    $_SESSION['sc'][$new] = array("ID" =&gt; $_GET['p'], "amount" =&gt; 1);
</pre>
<p>So $new contains the new array id for the new product. This is equal to the amount of products because, as mentioned before, product 1 has the index 0. So the last product&#8217;s index is the amount of products -1, and we just count one plus that and we&#8217;d get our new product index. And we all know -1+1 = 0 So we can leave that out and just count the products and use that number as the new index for the new product added.<br />
Then we add the product by creating a sub-array with the id and amount. The ID is here set to $_GET['p'], so cart.php?p=1 would add product id 1 ($_GET['p'] = 1).</p>
<p>Though we could now add one product twice, which would bug the system as there&#8217;s also already an amount set inside the product sub-array (ID and Amount is set for each product). So we need to check whether the product isn&#8217;t already in the shopping cart array. We can do this with the following for loop:</p>
<pre name="code" class="php:nogutter">for($index=0;$index&lt;$products;$index++) {

    if($_GET['p'] == $_SESSION['sc'][$index]['ID']) {

        $index_exists = true;

    }

}
</pre>
<p>Let&#8217;s go through this code. What it basicly does is set a variable $index to 0 ( the first product&#8217;s index ) and execute the loop for each index (product in the shopping cart array), which are the indexes 0 &#8211; ($products-1) in other words: $index&lt;$products. Then for each product we need to check if the ID ($_SESSION['sc'][$index]['id']) is equal to the id of the product requested to be added ($_GET['p']). If this is the case for any of the products, $index_exists will be set to true. So when $index_exists is set to true, there was a product found with the ID requested to be added. In that case the product was already added to the shopping cart earlier.</p>
<p>Thus we just need to check if $index_exists is equal to true, if so: the product is already in the shopping cart -&gt; show error message:</p>
<pre name="code" class="php:nogutter">if($index_exists) {

    echo "&lt;p&gt;Product already added &lt;/p&gt;";

}else{

    ///... else - product was not added earlier already -&gt; add the product

}
</pre>
<p>Otherwise ( else ) the product wasn&#8217;t found in the shopping cart so it will be added successfully. We can there put our &#8216;product add&#8217; code:</p>
<blockquote><p>$new = count($_SESSION['sc']);<br />
$_SESSION['sc'][$new] = array(&#8220;ID&#8221; =&gt; $_GET['p'], &#8220;amount&#8221; =&gt; 1);</p></blockquote>
<p>=&gt;</p>
<pre name="code" class="php:nogutter">if(isset($index_exists)) {

    echo "&lt;p&gt;Product already added &lt;/p&gt;";

}else{

    ///... else - product was not added earlier already -&gt; add the product
    $new = count($_SESSION['sc']);
    $_SESSION['sc'][$new] = array("ID" =&gt; $_GET['p'], "amount" =&gt; 1);

}
</pre>
<p>Let&#8217;s put that all together again:</p>
<pre name="code" class="php:nogutter">&lt;php
   session_start();

  if(!isset($_SESSION['sc']))
     $_SESSION['sc'] = array();

 $products = count($_SESSION['sc']);
 if($products &gt; 0) { //if there are more than 0 products in the shopping cart

   for($curr=0;$curr&lt;$products;$curr++) {

     foreach( $_SESSION['sc'][$curr] as $key =&gt; $value ) {

          echo $key.":".$value." &lt;br /&gt;";

      }
   }

 }else{

    echo "Empty";

 }

if($_GET['act'] == 'add' AND $_GET['p']) {

for($index=0;$index&lt;$products;$index++) {

    if($_GET['p'] == $_SESSION['sc'][$index]['id']) {

        $index_exists = true;

    }

}

if(isset($index_exists)) {

     echo "&lt;p&gt;Product already added &lt;/p&gt;";

 }else{

     ///... else - product was not added earlier already -&gt; add the product
    $new = count($_SESSION['sc']);
      $_SESSION['sc'][$new] = array("id" =&gt; $_GET['p'], "amount" =&gt; 1);

 }

}

?&gt;
</pre>
<p>We used an if loop which checks if $_GET['act'] == &#8216;add&#8217; and $_GET['p'] exists, which is the case when you go to the url like &#8216;cart.php?act=add&amp;p=product_id&#8217;. So when you link the user there, the product_id will be added to the shoppingcart.</p>
<p>Example link:</p>
<pre class="html:nogutter">&lt;a href='cart.php?act=add&amp;p=1'&gt;Add product #1&lt;/a&gt;
</pre>
<h3>Function &#8211; Clear Shopping Cart</h3>
<p><strong>Function to clear the shopping cart</strong></p>
<p>Allright, now we&#8217;ll create a function to clear the shopping cart. Which just unsets the whole session &#8217;sc&#8217;:</p>
<pre name="code" class="php:nogutter">if($_GET['act'] == 'clear') {

   unset($_SESSION['sc']);

}
</pre>
<p>We use the function unset to unset the session shopping cart. We&#8217;ll do this when the user requests the url cart.php?act=clear, as in that case the GET variable &#8216;act&#8217; has = &#8216;clear&#8217; ($_GET['act'] = &#8216;clear&#8217;). Which it checks in the if loop. So you can make a link to that url to make it clear the shopping cart. Like:</p>
<pre class="html:nogutter">&lt;a href='cart.php?act=clear'&gt;Empty Shopping Cart&lt;/a&gt;
</pre>
<h3>Function &#8211; Update Products</h3>
<p><strong>Function to update the amount of each product of the shopping cart</strong></p>
<p>Allright, now we&#8217;ve came to the last function which is to change the amount of a product. Which is just changing the sub-variable &#8216;amount&#8217; of the array $_SESSION['sc'][product_array_id]. For example:</p>
<pre name="code" class="php:nogutter">$_SESSION['sc'][0]['amount'] = 10;
//changes the product with array index 0 - sets the amount sub-variable of the product to 10.
</pre>
<p>We&#8217;ll need a form to make the user fill in an amount for a product. For each product we&#8217;ll need to make this form ( so the user can added the amount for each product ). So we&#8217;ll need to add this form inside the loop where it retrieves all products in the shopping cart. Which was the following code ( remember? ) :</p>
<pre name="code" class="php:nogutter">   for($curr=0;$curr&lt;$products;$curr++) {

      foreach( $_SESSION['sc'][$curr] as $key =&gt; $value ) {

           echo $key.":".$value." &lt;br /&gt;";

       }

   }
</pre>
<p>Which we created in the beginning of the tutorial. We&#8217;re going to add this form to it:</p>
<pre name="code" class="php:nogutter">    echo "&lt;form method='POST' action='cart.php?aid=".$curr."'&gt;&lt;p&gt;
Change amount: &lt;input type='text' name='amount' value='".$_SESSION['sc'][$curr]['amount']."'&gt;
&lt;input type='submit' name='submit' value='update'&gt;
&lt;/form&gt;";
</pre>
<p>Let&#8217;s have a look at that form. It uses the method POST, which means it puts all user input into $_POST['form_field_name'] variables when the form is submitted. It goes to the page &#8216;cart.php?aid=&#8221;.$curr.&#8221;&#8216; which means it creates the GET variable $_GET['aid'] and sets it equal to $curr, which contains the array index of the current product that&#8217;s been updated/changed the amount of. Then we&#8217;ve got one field named &#8216;amount&#8217; which has the value of $_SESSION['sc'][$curr]['amount'], which is the amount of the current product ($_SESSION['sc'][$curr] is the current product sub-array containing amount and ID index, we take the ['amount'] sub-variable).</p>
<p>Put it together:</p>
<pre name="code" class="php:nogutter">   for($curr=0;$curr&lt;$products;$curr++) {

       foreach( $_SESSION['sc'][$curr] as $key =&gt; $value ) {

            echo $key.":".$value." &lt;br /&gt;";

        }

    echo "&lt;form method='POST' action='cart.php?aid=".$curr."'&gt;&lt;p&gt;
Change amount: &lt;input type='text' name='amount' value='".$_SESSION['sc'][$curr]['amount']."'&gt;
&lt;input type='submit' name='submit' value='update'&gt;
&lt;/form&gt;";

     }
</pre>
<p>Let&#8217;s update the old for loop and put it all together:</p>
<pre name="code" class="php:nogutter"> &lt;php
    session_start();

   if(!isset($_SESSION['sc']))
      $_SESSION['sc'] = array();

  $products = count($_SESSION['sc']);
  if($products &gt; 0) { //if there are more than 0 products in the shopping cart

####UPDATED####

    for($curr=0;$curr&lt;$products;$curr++) {

        foreach( $_SESSION['sc'][$curr] as $key =&gt; $value ) {

             echo $key.":".$value." &lt;br /&gt;";

         }

    echo "&lt;form method='POST' action='cart.php?aid=".$curr."'&gt;&lt;p&gt;
 Change amount: &lt;input type='text' name='amount' value='".$_SESSION['sc'][$curr]['amount']."'&gt;
 &lt;input type='submit' name='submit' value='update'&gt;
 &lt;/form&gt;";

      }

  }else{

     echo "Empty";

  }

if($_GET['act'] == 'add' AND $_GET['p']) {

for($index=0;$index&lt;$products;$index++) {

     if($_GET['p'] == $_SESSION['sc'][$index]['id']) {

         $index_exists = true;

     }

 }

if(isset($index_exists)) {

      echo "&lt;p&gt;Product already added &lt;/p&gt;";

  }else{

      ///... else - product was not added earlier already -&gt; add the product
     $new = count($_SESSION['sc']);
       $_SESSION['sc'][$new] = array("id" =&gt; $_GET['p'], "amount" =&gt; 1);

  }

}

###########ADDED############

if($_GET['act'] == 'clear') {

   unset($_SESSION['sc']);

}

?&gt;
</pre>
<p>Ok, so when the user tries to update the amount of a product, the variable $_GET['aid'] will be containing the array index of the product and $_POST['amount'] will contain the user filled in amount in the form field &#8216;amount&#8217;.</p>
<p>To check if the user tried to change the amount of a product, we simply check if $_POST['amount'] exists and if not empty:</p>
<pre name="code" class="php:nogutter">if(!empty($_POST['amount'])) {

   //update amount

}
</pre>
<p>Let&#8217;s put the array id ($_GET['aid']) inside a variable $array_id and the amount the user filled in for that product ($_POST['amount']) inside a variable $amount:</p>
<pre name="code" class="php:nogutter">    $array_id = $_GET['aid'];

    $amount = $_POST['amount'];
</pre>
<p>Now we need to change the amount of the product with the index $array_id. As all products are in the array $_SESSION['sc'], the product is $_SESSION['sc'][$array_id]. And to change the amount of that product we need to change the sub-variable &#8216;amount&#8217;. So it becomes: $_SESSION['sc'][$array_id]['amount'].<br />
We&#8217;ll set it equal to the user input = $amount, so:</p>
<pre name="code" class="php:nogutter">if(!empty($_POST['amount'])) {

   //update amount

    $array_id = $_GET['aid'];

     $amount = $_POST['amount'];

    $_SESSION['sc'][$array_id]['amount'] = $amount;

}
</pre>
<h3>Shopping Cart System &#8211; End Result</h3>
<p>We put it all together and we&#8217;re done with our &#8220;basic &#8221; shopping cart system!</p>
<p><strong>File: cart.php</strong></p>
<pre name="code" class="php:nogutter">  &lt;php
session_start();

if(!isset($_SESSION['sc']))
   $_SESSION['sc'] = array();

$products = count($_SESSION['sc']);

###########RETRIEVE PRODUCTS FUNCTION############

if($products &gt; 0) { //if there are more than 0 products in the shopping cart

   for($curr=0;$curr&lt;$products;$curr++) {

    foreach( $_SESSION['sc'][$curr] as $key =&gt; $value ) {

        echo $key.":".$value." &lt;br /&gt;";

    }

    echo "&lt;form method='POST' action='cart.php?aid=".$curr."'&gt;&lt;p&gt;
Change amount: &lt;input type='text' name='amount' value='".$_SESSION['sc'][$curr]['amount']."'&gt;
&lt;input type='submit' name='submit' value='update'&gt;
&lt;/form&gt;";

   }

}else{

   echo "Empty";

}

###########ADD FUNCTION############
if($_GET['act'] == 'add' AND $_GET['p']) {

for($index=0;$index&lt;$products;$index++) {

    if($_GET['p'] == $_SESSION['sc'][$index]['ID']) {

        $index_exists = true;

    }

}

if($index_exists) {

    echo "&lt;p&gt;Product already added &lt;/p&gt;";

}else{

    ///... else - product was not added earlier already -&gt; add the product
    $new = count($_SESSION['sc']);
    $_SESSION['sc'][$new] = array("ID" =&gt; $_GET['p'], "amount" =&gt; 1);
    echo "&lt;p&gt;".$_GET['p']." ID added for index ".$new."&lt;/p&gt;";

}

}

###########CLEAR FUNCTION############

if($_GET['act'] == 'clear') {

   unset($_SESSION['sc']);

}

###########ADDED - UPDATE FUNCTION############

if(!empty($_POST['amount'])) {

   //update amount

    $array_id = $_GET['aid'];

    $amount = $_POST['amount'];

    echo "&lt;p&gt;array id:".$array_id." and amount: ".$amount." and product id: ".$_SESSION['sc'][$array_id]['ID']."&lt;/p&gt;";

    $_SESSION['sc'][$array_id]['amount'] = $amount;
    echo $_SESSION['sc'][$array_id]['amount'];

}

?&gt;
</pre>
<p>This system was more complicated to explain because of the arrays and sub-arrays and because of it&#8217;s somewhat longer size ( script ). But hope you learnt something!</p>
<p>Cheers,<br />
Admin.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.webcodez.net/php-mysql/basic-shopping-cart-system/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Generate Random Passwords</title>
		<link>http://www.webcodez.net/php-mysql/generate-random-passwords/</link>
		<comments>http://www.webcodez.net/php-mysql/generate-random-passwords/#comments</comments>
		<pubDate>Thu, 21 Jan 2010 15:04:23 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[PHP & MySql]]></category>
		<category><![CDATA[arrays]]></category>
		<category><![CDATA[for loop]]></category>
		<category><![CDATA[functions]]></category>
		<category><![CDATA[loops]]></category>
		<category><![CDATA[net script]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[random]]></category>
		<category><![CDATA[variables]]></category>

		<guid isPermaLink="false">http://www.webcodez.net/?p=184</guid>
		<description><![CDATA[For generating passwords multiple methods can be used. In this tutorial we&#8217;ll be discussing 2 ways to generate random passwords. The result of both methods is exactly the same. Although method 1 is based on generating random indexes and picking another (random) index&#8217;s value each time when adding a new random character to the random [...]]]></description>
			<content:encoded><![CDATA[<p>For generating passwords multiple methods can be used. In this tutorial we&#8217;ll be discussing 2 ways to generate random passwords. The result of both methods is exactly the same. Although method 1 is based on generating random indexes and picking another (random) index&#8217;s value each time when adding a new random character to the random password. While method 2 is based on picking the same index but shuffling the values and indexes so that that index contains a different value each time.</p>
<p><strong>Method 1</strong><br />
We&#8217;ll start with the first method which uses these PHP functions:</p>
<p>    * str_split &#8211; converts a string into an array<br />
    * shuffle &#8211; shuffles an array (index and values)</p>
<p>What we need to create first, is a variable $charset which contains all characters and maybe symbols that we want the system to generate a random password out of. So the characters the password generated can/may contain.</p>
<p>Here I take for example all alphabetical characters and all numbers.</p>
<pre name="code" class="php:nogutter">
&lt;?php

$charset = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz012345678901234567890012345678901234567890";

?>
</pre>
<p>The numbers 0-9 I put in it 4 times because there are about 2 times as much alphabetical characters and they&#8217;re put inside it twice ( non-capital and capital) and I want to have about the same amount (chance) of characters as numbers inside the password.</p>
<p>What we want to do is create a function that generates a random password using random characters or numbers from our charset. We also need to be able to give the amount of chars to pick randomly out of the charset to create a password from ( the length of the random password ). So the argruments for the function should be: charset, length. Where charset is our $charset and length is the length of the password ( amount of random chars picked from the charset and put together ).</p>
<pre name="code" class="php:nogutter">
&lt;?php

function random_passw($charset, $length) {

   ... generate $length random chars out of $charset

}

$charset = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz012345678901234567890012345678901234567890";

$length = 8; //we set the length for our password to 8 chars for example

?>
</pre>
<p>So now we&#8217;ve come to the part of the function which needs to shuffle all characters of the charset. Therefore we first need to put it into an array as the shuffling is based on shuffling the indexes and values. We use the str_split function to put the charset in an array.</p>
<pre name="code" class="php:nogutter">
function random_passw($charset, $length) {

   $charset_arr = str_split($charset); //charset_array

}
</pre>
<p>So now the charset is put in an array like this:</p>
<blockquote><p>$charset_arr[0] = &#8220;A&#8221;;<br />
$charset_arr[1] = &#8220;B&#8221;;<br />
$charset_arr[2] = &#8220;C&#8221;;<br />
&#8230; etc &#8230;</p></blockquote>
<p>In this case the index 0 has the value &#8216;A&#8217;. We&#8217;ll make a loop which adds that index value to the password ( we&#8217;ll make a variable $passw ) the amount of times set in $length:</p>
<pre name="code" class="php:nogutter">
function random_passw($charset, $length) {

    $charset_arr = str_split($charset); //charset_array

    $passw = ""; //empty password to start with

  for($a=1;$a<=$length;$a++) { //as long as $a is smaller than or equal to $length
  //and increase $a each time the loop is executed

      $passw .= $charset_arr[0]; //add the value of the charset's first character (of index 0, which in this case is equal to the character 'A' )

   }

 }
</pre>
<p>So now it adds '$length' times the character 'A' to the variable $passw. So if we give the value 8 to the variable $length, it adds 'A' to the password 8 times, like:</p>
<blockquote><p>$passw = "AAAAAAAA";</p></blockquote>
<p>But we want it to add a different character to the set (password) each time it adds a character. To do this we use the function shuffle. This function will shuffle all indexes and values randomly - shuffle all chars in the charset in a random order. So say we first got our charset like:</p>
<pre name="code" class="php:nogutter">
$charset_arr = "ABC";
</pre>
<p>Which has the array:</p>
<pre name="code" class="php:nogutter">
$charset_arr[0] = "A";
$charset_arr[1] = "B";
$charset_arr[2] = "C";
</pre>
<p>It will shuffle all values for the indexes, so it could be shuffled like this then (for example, but it's random so it could be shuffled anyhow) :</p>
<pre name="code" class="php:nogutter">
$charset_arr[0] = "C";
$charset_arr[1] = "A";
$charset_arr[2] = "B";
</pre>
<p>So then the index 0 suddenly got the value "C" instead of "A". This way we can make it pick the same index but containing another value for our index '0' each time and this way pick random characters out of the charset.</p>
<pre name="code" class="php:nogutter">
function random_passw($charset, $length) {

     $charset_arr = str_split($charset); //charset_array

    $passw = ""; //empty password to start with

  for($a=1;$a<=$length;$a++) { //as long as $a is smaller than or equal to $length
  //and increase $a each time the loop is executed

      $shuffled = shuffle($charset_arr); //shuffles the indexes and values - in other words: shuffles the chars in the charset in a random order
      $passw .= $shuffled[0]; //take the value of the index '0' of the SHUFFLED charset - the first character of the shuffled charset which is different each time it's shuffled ( which is each time the loop is executed / shuffle function executed )

      }

  }
</pre>
<p>Last thing we need to do is make it return the password generated, which can be done using the function return.</p>
<pre name="code" class="php:nogutter">
function random_passw($charset, $length) {

     $charset_arr = str_split($charset); //charset_array

    $passw = ""; //empty password to start with

  for($a=1;$a<=$length;$a++) { //as long as $a is smaller than or equal to $length
  //and increase $a each time the loop is executed

      $shuffled = shuffle($charset_arr); //shuffles the indexes and values - in other words: shuffles the chars in the charset in a random order
      $passw .= $shuffled[0]; //take the value of the index '0' of the SHUFFLED charset - the first character of the shuffled charset which is different each time it's shuffled ( which is each time the loop is executed / shuffle function executed )

     }

     return($passw);

  }
</pre>
<p>And we're done!</p>
<p>Example of use:</p>
<pre name="code" class="php:nogutter">
function random_passw($charset, $length) {

     $charset_arr = str_split($charset); //charset_array

    $passw = ""; //empty password to start with

  for($a=1;$a<=$length;$a++) { //as long as $a is smaller than or equal to $length
  //and increase $a each time the loop is executed

      $shuffled = shuffle($charset_arr); //shuffles the indexes and values - in other words: shuffles the chars in the charset in a random order
      $passw .= $shuffled[0]; //take the value of the index '0' of the SHUFFLED charset - the first character of the shuffled charset which is different each time it's shuffled ( which is each time the loop is executed / shuffle function executed )
  }

  }

$charset = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz012345678901234567890012345678901234567890";
$length = 8;

$password = random_passw($charset, $length);

echo "Your password is: ".$password;

?>
</pre>
<p><strong>Method 2</strong></p>
<p>Functions used:</p>
<p>    * mt_rand($first, $last) - generates random number between $first and $last<br />
    * length($str) - calculates the length of the string $str</p>
<p>What we basicly did in the first method was adding the same index's value of the charset. But we made it contain another value each time by suffling the values of the indexes. Now we'll keep our charset in the same 'order' ( so each index keeps the same value ). But this time we'll change the index we request the value of each time we do so. So this way it requests another index's value ( and so another character ) each time we add a new character to the password. In other words: we add random characters to the password. We'll again use our charset and length variables:</p>
<pre name="code" class="php:nogutter">
&lt;?php

$charset = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz012345678901234567890012345678901234567890";

$length = 8; //we set the length for our password to 8 chars for example

?>
</pre>
<p>And now create a function which generates the random characters. We'll therefore again use a for loop to make it add a new random character to the password string as many times as set in $length. So the password will be the length of $length.</p>
<pre name="code" class="php:nogutter">
function random_passw($charset, $length) {

   $passw = "";

   for($a=1;$a<=$length;$a++) {

       //add a random character to the $passw

   }

}
</pre>
<p>We again use the same loop and set a variable $passw in the beginning to empty. We'll be adding the random characters to it inside the for loop. The charset is now already having indexes and values for each character, like this:</p>
<pre name="code" class="php:nogutter">
$charset[0] = "A";
$charset[1] = "B";
$charset[2] = "C";
... etc ...
</pre>
<p>Just because we got the characters in this order inside the variable:</p>
<blockquote><p>$charset = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz012345678901234567890012345678901234567890";
</p></blockquote>
<p>You see the first character 'A' has been given the index 0. Now what we basicly need to do for adding a random character, is generating a random index for the array ( and so a random value/character corresponding to that index ). Which is generating a random number from 0 ( the first index ) to the last index. The last index can be generated by counting the amount of characters minus 1. Because the first character hasn't been given the index 1 but 0, and for the second character it's 1, etc.. So for the last character's index it's the amount of characters minus one. The amount of characters can be calculated using the length function:</p>
<pre name="code" class="php:nogutter">
function random_passw($charset, $length) {

   $passw = "";

   for($a=1;$a<=$length;$a++) {

       $first_index = 0;
       $last_index = length($charset)-1;

   }

}
</pre>
<p>Now we need to generate a random number between the first and last index ( 0 - $last_index ). We can use the function mt_rand to do this.</p>
<pre name="code" class="php:nogutter">
function random_passw($charset, $length) {

    $passw = "";

    for($a=1;$a<=$length;$a++) {

        $first_index = 0;
       $last_index = length($charset)-1;

       $index = mt_rand($first_index, $last_index); //generates random index

    }

 }
</pre>
<p>Now we got a random index we generated in the variable $index. And because it's a number between the first and last index of the charset, we are sure it has a value. Which is one of the characters of the charset. Which we can call like $charset[index] ( as it's $array[index], and the charset can be seen a special kind of array where each index has one value ( the next character in the string ) ). And as the random index we generated is in the variable $index, it becomes $charset[$index] for us.So we'll add that value to the password:</p>
<pre name="code" class="php:nogutter">
 function random_passw($charset, $length) {

     $passw = "";

     for($a=1;$a<=$length;$a++) {

         $first_index = 0;
         $last_index = length($charset)-1;

       $index = mt_rand($first_index, $last_index); //generates random index

       $passw .= $charset[$index];

     }

  }
 </pre>
<p>Allright, so now it adds a value of a random index ( and so a random character of the charset ) to the $passw variable. And it does this $length many times. In other words: it creates a random pasword with the length of $length.</p>
<p>Now the last thing to do is actually returning the password:</p>
<pre name="code" class="php:nogutter">
  function random_passw($charset, $length) {

      $passw = "";

      for($a=1;$a<=$length;$a++) {

          $first_index = 0;
         $last_index = length($charset)-1;

        $index = mt_rand($first_index, $last_index); //generates random index

       $passw .= $charset[$index];

      }

   return($passw);

   }
  </pre>
<p>Which is, easy as it gets, the function return. And the random password generator function is done!<br />
It has the same use as the previous one explained in method 1, so enjoy!</p>
<p>Cheers,<br />
Admin.</p>
<p>Btw, realised the first method wasn't that much faster afterall lol </p>
]]></content:encoded>
			<wfw:commentRss>http://www.webcodez.net/php-mysql/generate-random-passwords/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>For Loop</title>
		<link>http://www.webcodez.net/php-mysql/for-loop/</link>
		<comments>http://www.webcodez.net/php-mysql/for-loop/#comments</comments>
		<pubDate>Sat, 16 Jan 2010 09:54:35 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[PHP & MySql]]></category>
		<category><![CDATA[basics]]></category>
		<category><![CDATA[for loop]]></category>
		<category><![CDATA[fundamentals]]></category>
		<category><![CDATA[loops]]></category>
		<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false">http://www.webcodez.net/wordpress/?p=100</guid>
		<description><![CDATA[Then we’ve got the for loop. This loop is in some point of view kind of smilar to the while loop as it as well repeats a certain code several times. Though, the for loop requires a variable to be set, an increment value (or decrement) and a condition, as argruments of the loop. A [...]]]></description>
			<content:encoded><![CDATA[<p>Then we’ve got the for loop. This loop is in some point of view kind of smilar to the while loop as it as well repeats a certain code several times. Though, the for loop requires a variable to be set, an increment value (or decrement) and a condition, as argruments of the loop. A basic example of a for loop looks like this (structure) :</p>
<pre name="code" class="php:nogutter">
for ( set variable; condition; action increment/decrement ) {

            ...act code...

}
</pre>
<p>Say we want to set a begin value (we use the variable named $i, which is a common name for integer variables to be used) to 0 and we want to let it count to 10.</p>
<p>Example:</p>
<pre name="code" class="php:nogutter">
for ( $i = 0; $i <= 10; $i++ ) {

            echo $i;

}
</pre>
<p>The variable set is $i, which we set to 0. The condition for the code to be ran is that $i is smaller than or equal to 10. So as long as this is the case, the value of $i will be shown on the screen (echo $i). Each time it shows $i on the screen, $i will be increased by 1 ($i++) and the loop will be repeated as long as the condition ($i<=10) is still true. In other words: it shows the value of $i on the screen, increases it by 1, shows it on the screen again, etc., and repeats this until $i is equal to 10.</p>
<p>Output:</p>
<blockquote><p>
1<br />
2<br />
3<br />
4<br />
5<br />
6<br />
7<br />
8<br />
9<br />
10
</p></blockquote>
<p>You could also make it count downwards:</p>
<pre name="code" class="php:nogutter">
for ( $i = 10; $i => 0; $i--) {

            echo $i;

}
</pre>
<p>You see we now set $i (begin value) to 10 and set the condition to $i is larger or equal to 0, and the action to repeat each time the loop is executed to $i--(which means: decrease $i by 1).</p>
<p>Admin.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.webcodez.net/php-mysql/for-loop/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
