<?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>Foreach &#8211; stoimen&#039;s web log</title>
	<atom:link href="/tag/foreach/feed/" rel="self" type="application/rss+xml" />
	<link></link>
	<description>on web development</description>
	<lastBuildDate>Tue, 13 Feb 2018 08:18:15 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>https://wordpress.org/?v=5.0.3</generator>
	<item>
		<title>PHP: Arrays or Linked Lists?</title>
		<link>/2012/07/24/php-arrays-or-linked-lists/</link>
		<comments>/2012/07/24/php-arrays-or-linked-lists/#comments</comments>
		<pubDate>Tue, 24 Jul 2012 11:25:20 +0000</pubDate>
		<dc:creator><![CDATA[Stoimen]]></dc:creator>
				<category><![CDATA[data structures]]></category>
		<category><![CDATA[$_head]]></category>
		<category><![CDATA[C]]></category>
		<category><![CDATA[Comparison of programming languages]]></category>
		<category><![CDATA[Data structures]]></category>
		<category><![CDATA[Data types]]></category>
		<category><![CDATA[Extinction]]></category>
		<category><![CDATA[Foreach]]></category>
		<category><![CDATA[Linked list]]></category>
		<category><![CDATA[List]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Pointer]]></category>
		<category><![CDATA[Stack]]></category>
		<category><![CDATA[UnShuffle sort]]></category>

		<guid isPermaLink="false">/?p=3259</guid>
		<description><![CDATA[Arrays vs. Linked List If we talk about arrays and linked lists we know the pros and cons about both of them. No matter which programming language we use arrays benefit from direct access to its items, while linked lists are more memory efficient for particular tasks. The items of a linked list keep a &#8230; <a href="/2012/07/24/php-arrays-or-linked-lists/" class="more-link">Continue reading <span class="screen-reader-text">PHP: Arrays or Linked Lists?</span> <span class="meta-nav">&#8594;</span></a><div class='yarpp-related-rss'>

Related posts:<ol>
<li><a href="/2012/06/14/computer-algorithms-linked-list-data-structure/" rel="bookmark" title="Computer Algorithms: Linked List">Computer Algorithms: Linked List </a></li>
<li><a href="/2012/07/17/computer-algorithms-detecting-and-breaking-a-loop-in-a-linked-list/" rel="bookmark" title="Computer Algorithms: Detecting and Breaking a Loop in a Linked List">Computer Algorithms: Detecting and Breaking a Loop in a Linked List </a></li>
<li><a href="/2010/09/29/construct-a-sorted-php-linked-list/" rel="bookmark" title="Construct a Sorted PHP Linked List">Construct a Sorted PHP Linked List </a></li>
<li><a href="/2012/08/17/its-not-true-that-php-arrays-are-copied-by-value/" rel="bookmark" title="It&#8217;s Not True that PHP Arrays are Copied by Value">It&#8217;s Not True that PHP Arrays are Copied by Value </a></li>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<h2>Arrays vs. Linked List</h2>
<p>If we talk about arrays and linked lists we know the pros and cons about both of them. No matter which programming language we use arrays benefit from direct access to its items, while linked lists are more memory efficient for particular tasks.</p>
<figure id="attachment_3279" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/07/Array-Linked-List.png"><img src="/wp-content/uploads/2012/07/Array-Linked-List.png" alt="Array &amp; Linked List" title="Array &amp; Linked List" width="620" height="314" class="size-full wp-image-3279" srcset="/wp-content/uploads/2012/07/Array-Linked-List.png 620w, /wp-content/uploads/2012/07/Array-Linked-List-300x151.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">Array &#038; Linked List</figcaption></figure>
<p>The items of a linked list keep a reference to their successor, so we can easily walk through the entire list. However we don&#8217;t have direct access to its elements. Thus we can&#8217;t go directly to its middle element! Even more &#8211; in particular implementations of a linked list we don&#8217;t know its length. But in some cases linked lists are far more effective than arrays. For instance reversing an array of non-numeric values require constant additional memory, but also requires n/2 exchanges. The same taks using linked lists is not only performed in linear time, but doesn&#8217;t require any additional memory. The only thing we need to do is to reverse the links &#8211; no movement of values and the items remain at the same place in the memory. </p>
<p>Merging of two arrays often require more space (proportional of the space of the two arrays) or many exchanges in case we try to do it in place. The same task on linked lists is far more effective with only changing pointers and without moving the values.<span id="more-3259"></span></p>
<h2>Arrays or Linked Lists are More Memory Efficient</h2>
<p>Many developers consider linked lists as something used only in college, but actually they can be very useful in practice as well. However how practically useful they are? Let&#8217;s see the following PHP experiment.</p>
<p>Here we have one class called &#8220;Item&#8221;, which is designed to keep only one integer value as its key and to point to its successor. Practically this class is designed to be used by a singly linked list, but let say we put some of these objects into an array and the same amount of the &#8220;Item&#8221; objects into a linked lists so what are the results?</p>
<p>First let&#8217;s see the code!</p>
<pre lang="PHP">
class Item
{
    protected $_key = '';
    protected $_next = null;
    
    public function __construct($key)
    {
        $this->_key = $key;
    }
    
    public function setNext(&$next) { $this->_next = $next; }
    public function &getNext() { return $this->_next; }
    
    public function setKey($key) { $this->_key = $key; }
    public function getKey() { return $this->_key; }
    
    public function __toString()
    {
        return $this->_key . "\n";
    }
}
</pre>
<p>This is the &#8220;Item&#8221; class and here we have the Linked_List class. As you can see this is the very basic implementation of a linked list with only one &#8220;insert&#8221; method and the magic __toString() in order to print the entire list. The insert method pushes an item at the end of the list thus the insertion is O(1).</p>
<pre lang="PHP">
class Linked_List 
{
    protected $_head = null;
    protected $_tail = null;
    
    public function insert($item)
    {
        if ($this->_head == null) {
            $this->_head = $item;
            $this->_tail = $item;
            return;
        }
        
        $this->_tail->setNext($item);
        $this->_tail = $item;
    }
    
    public function __toString()
    {
        $current = $this->_head;
        $output = '';
        
        while ($current) {
            $output .= $current->getKey() . "\n";
            $current = $current->getNext();
        }
        
        return $output;
    }
}
</pre>
<p>Now let&#8217;s see the creation of an array with N objects of class &#8220;Item&#8221;.</p>
<pre lang="PHP">
$n = 10000;
$a = array();
for ($i = 0; $i < $n; $i++) {
    $a[$i] = new Item($i);
}
</pre>
<p>The same thing but using the Linked_List class follows on the lines below.</p>
<pre lang="PHP">
$n = 10000;
$a = new Linked_List();
for ($i = 0; $i < $n; $i++) {
    $a->insert(new Item($i));
}
</pre>
<h2>And the Winner is ...</h2>
<p>More memory efficient is ... the linked list! On the next chart we can see the results. It's clear that for 10K objects the array uses nearly 1MB more memory than the linked list! </p>
<figure id="attachment_3280" style="width: 600px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/07/Array-vs.-Linked-List-Chart.png"><img src="/wp-content/uploads/2012/07/Array-vs.-Linked-List-Chart.png" alt="Array vs. Linked List Chart" title="Array vs. Linked List Chart" width="600" height="371" class="size-full wp-image-3280" srcset="/wp-content/uploads/2012/07/Array-vs.-Linked-List-Chart.png 600w, /wp-content/uploads/2012/07/Array-vs.-Linked-List-Chart-300x185.png 300w" sizes="(max-width: 600px) 100vw, 600px" /></a><figcaption class="wp-caption-text">&nbsp;</figcaption></figure>
<p>So what do you think now? Will you use linked list in your code or not?</p>
<h2>Final Words</h2>
<p>Although the linked list seems to be more memory efficient we don't have direct acess to it's items. In the same time often we don't need direct access, we just need to walk through the array, which doesn't benefit from the direct access. In PHP this is usally done with some loop construction as "foreach". So why we have such results in the experiment above. First our linked list is really very basic. It doesn't have any functionality, which in fact shouldn't affect memory usage much more. The array in the other hand keeps indexes for each of its items so this results in additional space. This explains a bit the victory of the linked list in the memory efficiency test.</p>
<p>In the other hand PHP can't have the full benefit of using linked lists, trees and other data structures since it keeps them in memory only for the request. In this case C, C++, Java loads a data structure in memory till the software runs so unfortunately coding complex data structures in PHP doesn't look as a great option. Indeed here we have an entire "Item" class only to keep an integer. Instead we can use an array of integers! </p>
<div class='yarpp-related-rss'>
<p>Related posts:<ol>
<li><a href="/2012/06/14/computer-algorithms-linked-list-data-structure/" rel="bookmark" title="Computer Algorithms: Linked List">Computer Algorithms: Linked List </a></li>
<li><a href="/2012/07/17/computer-algorithms-detecting-and-breaking-a-loop-in-a-linked-list/" rel="bookmark" title="Computer Algorithms: Detecting and Breaking a Loop in a Linked List">Computer Algorithms: Detecting and Breaking a Loop in a Linked List </a></li>
<li><a href="/2010/09/29/construct-a-sorted-php-linked-list/" rel="bookmark" title="Construct a Sorted PHP Linked List">Construct a Sorted PHP Linked List </a></li>
<li><a href="/2012/08/17/its-not-true-that-php-arrays-are-copied-by-value/" rel="bookmark" title="It&#8217;s Not True that PHP Arrays are Copied by Value">It&#8217;s Not True that PHP Arrays are Copied by Value </a></li>
</ol></p>
</div>
]]></content:encoded>
			<wfw:commentRss>/2012/07/24/php-arrays-or-linked-lists/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Thing to Know About PHP Arrays</title>
		<link>/2011/10/19/thing-to-know-about-php-arrays/</link>
		<comments>/2011/10/19/thing-to-know-about-php-arrays/#respond</comments>
		<pubDate>Wed, 19 Oct 2011 15:18:47 +0000</pubDate>
		<dc:creator><![CDATA[Stoimen]]></dc:creator>
				<category><![CDATA[micro tutorial]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Arrays]]></category>
		<category><![CDATA[C programming language]]></category>
		<category><![CDATA[Comparison of programming languages]]></category>
		<category><![CDATA[Computer programming]]></category>
		<category><![CDATA[Computing]]></category>
		<category><![CDATA[Data structures]]></category>
		<category><![CDATA[Data types]]></category>
		<category><![CDATA[Foreach]]></category>
		<category><![CDATA[how-to]]></category>
		<category><![CDATA[interpreter]]></category>
		<category><![CDATA[PHP arrays]]></category>
		<category><![CDATA[PHP micro tutorial]]></category>
		<category><![CDATA[php tutorial]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[tutorial]]></category>
		<category><![CDATA[web development]]></category>
		<category><![CDATA[webdev]]></category>

		<guid isPermaLink="false">/?p=2390</guid>
		<description><![CDATA[Consider the following case. We have an array with identical keys. $arr = array(1 => 10, 1 => 11); What happens when the interpreter reaches this line of code? This is not a syntax error and it is completely valid. Very similar, but more interesting case is when we have an array of identical keys, &#8230; <a href="/2011/10/19/thing-to-know-about-php-arrays/" class="more-link">Continue reading <span class="screen-reader-text">Thing to Know About PHP Arrays</span> <span class="meta-nav">&#8594;</span></a><div class='yarpp-related-rss'>

Related posts:<ol>
<li><a href="/2010/08/31/php-what-is-more-powerful-than-list-perhaps-extract/" rel="bookmark" title="PHP: What is More Powerful Than list() &#8211; Perhaps extract()">PHP: What is More Powerful Than list() &#8211; Perhaps extract() </a></li>
<li><a href="/2012/07/24/php-arrays-or-linked-lists/" rel="bookmark" title="PHP: Arrays or Linked Lists?">PHP: Arrays or Linked Lists? </a></li>
<li><a href="/2010/05/19/php-associative-arrays-coding-style/" rel="bookmark" title="PHP Associative Arrays Coding Style">PHP Associative Arrays Coding Style </a></li>
<li><a href="/2010/06/11/friday-algorithms-quicksort-difference-between-php-and-javascript/" rel="bookmark" title="Friday Algorithms: Quicksort &#8211; Difference Between PHP and JavaScript">Friday Algorithms: Quicksort &#8211; Difference Between PHP and JavaScript </a></li>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<p>Consider the following case. We have an array with identical keys. </p>
<pre lang="PHP">
$arr = array(1 => 10, 1 => 11);
</pre>
<p>What happens when the interpreter reaches this line of code? This is not a syntax error and it is completely valid. Very similar, but more interesting case is when we have an array of identical keys, where those identical keys are represented once as an integer and then as a string.<br />
<figure id="attachment_2404" style="width: 640px" class="wp-caption aligncenter"><a href="/wp-content/uploads/2011/10/php.code_.jpg"><img src="/wp-content/uploads/2011/10/php.code_.jpg" alt="Keys in PHP arrays are not type sensitive, so pay attention when using them!" title="PHP Code" width="640" height="480" class="size-full wp-image-2404" srcset="/wp-content/uploads/2011/10/php.code_.jpg 640w, /wp-content/uploads/2011/10/php.code_-300x225.jpg 300w" sizes="(max-width: 640px) 100vw, 640px" /></a><figcaption class="wp-caption-text">Keys in PHP arrays are not type sensitive, so pay attention when using them!</figcaption></figure></p>
<pre lang="PHP">
$arr = array(1 => 10, "1" => 11);
</pre>
<p>Now several questions arise. First of all, how many elements have this array? Two or one. This can be easily verified by checking what count() will return.<span id="more-2390"></span></p>
<pre lang="PHP">
echo count($arr);
</pre>
<p>The correct answer is 1. This simply means, that there&#8217;s no difference between string keys and integer keys. What would happen if we had a &#8220;normal&#8221; array with different keys?</p>
<pre lang="PHP">
$arr = array(1 => 10, "2" => 11);
echo count($arr);
</pre>
<p>As expected this returns 2. </p>
<p>Next thing to check is what&#8217;s in the array after this initialization line.</p>
<pre lang="PHP">
$arr = array(1 => 10, "1" => 11);
</pre>
<p>Is there something in the first element $arr[0], or there&#8217;s something in the second element $arr[1]? What is the value of the single value?<br />
As it appears the second element replaces the first one. We&#8217;ve seen that the array has only one value, but where&#8217;s that value? The only way to check this is to dump both elements:</p>
<pre lang="PHP">
var_dump($arr);
</pre>
<p>Here we can see that $arr[1] contains &#8220;11&#8221; and it is the only value, and $arr[0] is not set.</p>
<div class='yarpp-related-rss'>
<p>Related posts:<ol>
<li><a href="/2010/08/31/php-what-is-more-powerful-than-list-perhaps-extract/" rel="bookmark" title="PHP: What is More Powerful Than list() &#8211; Perhaps extract()">PHP: What is More Powerful Than list() &#8211; Perhaps extract() </a></li>
<li><a href="/2012/07/24/php-arrays-or-linked-lists/" rel="bookmark" title="PHP: Arrays or Linked Lists?">PHP: Arrays or Linked Lists? </a></li>
<li><a href="/2010/05/19/php-associative-arrays-coding-style/" rel="bookmark" title="PHP Associative Arrays Coding Style">PHP Associative Arrays Coding Style </a></li>
<li><a href="/2010/06/11/friday-algorithms-quicksort-difference-between-php-and-javascript/" rel="bookmark" title="Friday Algorithms: Quicksort &#8211; Difference Between PHP and JavaScript">Friday Algorithms: Quicksort &#8211; Difference Between PHP and JavaScript </a></li>
</ol></p>
</div>
]]></content:encoded>
			<wfw:commentRss>/2011/10/19/thing-to-know-about-php-arrays/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>PHP: Fetch $_GET as String with http_build_query()</title>
		<link>/2011/08/17/php-fetch-get-as-string-with-http_build_query/</link>
		<comments>/2011/08/17/php-fetch-get-as-string-with-http_build_query/#comments</comments>
		<pubDate>Wed, 17 Aug 2011 07:42:24 +0000</pubDate>
		<dc:creator><![CDATA[Stoimen]]></dc:creator>
				<category><![CDATA[micro tutorial]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Computing]]></category>
		<category><![CDATA[D]]></category>
		<category><![CDATA[elegant solution]]></category>
		<category><![CDATA[Foreach]]></category>
		<category><![CDATA[http]]></category>
		<category><![CDATA[http_build_query]]></category>
		<category><![CDATA[php reference]]></category>
		<category><![CDATA[Query string]]></category>
		<category><![CDATA[Scripting languages]]></category>
		<category><![CDATA[String]]></category>
		<category><![CDATA[URL]]></category>
		<category><![CDATA[World Wide Web]]></category>

		<guid isPermaLink="false">/?p=2358</guid>
		<description><![CDATA[PHP is really full of functions for everything! Most of the time when you try to do something with strings, there&#8217;s a function that can do it better and faster. The Route from $_GET to String The global arrays in PHP contain request parameters. Either GET or POST. As you know if the page address &#8230; <a href="/2011/08/17/php-fetch-get-as-string-with-http_build_query/" class="more-link">Continue reading <span class="screen-reader-text">PHP: Fetch $_GET as String with http_build_query()</span> <span class="meta-nav">&#8594;</span></a><div class='yarpp-related-rss'>

Related posts:<ol>
<li><a href="/2011/08/18/powerful-php-less-known-string-manipulation/" rel="bookmark" title="Powerful PHP: Less Known String Manipulation">Powerful PHP: Less Known String Manipulation </a></li>
<li><a href="/2010/06/16/zend-examples-get-parameters-default-value/" rel="bookmark" title="Zend Examples: GET Parameters Default Value">Zend Examples: GET Parameters Default Value </a></li>
<li><a href="/2010/09/17/5-php-string-functions-you-need-to-know/" rel="bookmark" title="5 PHP String Functions You Need to Know">5 PHP String Functions You Need to Know </a></li>
<li><a href="/2010/09/08/http-post-with-php-without-curl/" rel="bookmark" title="HTTP POST with PHP without cURL">HTTP POST with PHP without cURL </a></li>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<p><strong>PHP</strong> is really full of functions for everything! Most of the time when you try to do something with strings, there&#8217;s a function that can do it better and faster. </p>
<h2>
The Route from $_GET to String<br />
</h2>
<p>The global arrays in PHP contain request parameters. Either <a href="http://php.net/manual/en/reserved.variables.get.php" title="PHP: $_GET - Manual" target="_blank">GET</a> or <a href="http://www.php.net/manual/en/reserved.variables.post.php" title="PHP: $_POST - Manual" target="_blank">POST</a>. As you know if the page address is something like:</p>
<pre lang="PHP">
http://www.example.com/index.php?a=b&key=value
</pre>
<p>This means that you pass to the index.php file two parameters &#8211; &#8220;a&#8221; and &#8220;key&#8221; with their values: &#8220;b&#8221; and &#8220;value&#8221;. Now in this case you can dump the $_GET <strong>global array</strong> somewhere in index.php and you&#8217;ll receive something like this.</p>
<pre lang="PHP">
array(
	"a"   => "b",
	"key" => "value",
);
</pre>
<p>This is however pseudocode, but in fact $_GET will be very similar to this sample array. <span id="more-2358"></span></p>
<h2>
$_GET to String<br />
</h2>
<p>Very often when a developer need to process the $_GET array to a string, which means generating again the query string from $_GET, he often comes to some operation like this one.</p>
<pre lang="PHP">
$queryString = '';
foreach ($_GET as $key => $value) {
	$queryString .= $key . '=' . $value . '&';
}
</pre>
<p>However this will result in something quite ugly like <b>a=b&#038;key=value&#038;</b> which comes with a trailing &#038; at the end of the string.</p>
<p>There is however another approach &#8211; using an array.</p>
<pre lang="PHP">
$queryString = array();
foreach ($_GET as $key => $value) {
	$queryString[] = $key . '=' . $value;
}
$queryString = implode('&', $queryString);
</pre>
<p>But that invokes one function more and this is still not the most elegant solution. As I said at the beginning PHP is full of useful functions and here comes the <a href="http://php.net/manual/en/function.http-build-query.php" title="PHP: http_build_query - Manual" target="_blank">http_build_query</a>.</p>
<h2>
http_build_query<br />
</h2>
<p>This is exactly what you need. As it name describe you can build the query string even by using a different from &#038; separator.</p>
<pre lang="PHP">
$queryString = http_build_query($_GET, '', '|');
</pre>
<p>Thus $queryString will contain <strong>a=b|key=value</strong> and at least the code will look pritier.</p>
<div class='yarpp-related-rss'>
<p>Related posts:<ol>
<li><a href="/2011/08/18/powerful-php-less-known-string-manipulation/" rel="bookmark" title="Powerful PHP: Less Known String Manipulation">Powerful PHP: Less Known String Manipulation </a></li>
<li><a href="/2010/06/16/zend-examples-get-parameters-default-value/" rel="bookmark" title="Zend Examples: GET Parameters Default Value">Zend Examples: GET Parameters Default Value </a></li>
<li><a href="/2010/09/17/5-php-string-functions-you-need-to-know/" rel="bookmark" title="5 PHP String Functions You Need to Know">5 PHP String Functions You Need to Know </a></li>
<li><a href="/2010/09/08/http-post-with-php-without-curl/" rel="bookmark" title="HTTP POST with PHP without cURL">HTTP POST with PHP without cURL </a></li>
</ol></p>
</div>
]]></content:encoded>
			<wfw:commentRss>/2011/08/17/php-fetch-get-as-string-with-http_build_query/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Using PHP&#8217;s array_diff in Algorithm Development</title>
		<link>/2010/10/03/using-php-array_diff-in-algorithm-development/</link>
		<comments>/2010/10/03/using-php-array_diff-in-algorithm-development/#comments</comments>
		<pubDate>Sun, 03 Oct 2010 10:51:54 +0000</pubDate>
		<dc:creator><![CDATA[Stoimen]]></dc:creator>
				<category><![CDATA[micro tutorial]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[array]]></category>
		<category><![CDATA[Arrays]]></category>
		<category><![CDATA[Computing]]></category>
		<category><![CDATA[Control flow]]></category>
		<category><![CDATA[Data structures]]></category>
		<category><![CDATA[Data types]]></category>
		<category><![CDATA[Foreach]]></category>
		<category><![CDATA[Notation]]></category>

		<guid isPermaLink="false">/?p=2010</guid>
		<description><![CDATA[array_diff can be really powerful. Once you&#8217;ve to find the different elements between two arrays you&#8217;ve to use array_diff. Here&#8217;s a case when you can use it while coding a simple algorithm. The Task You&#8217;ve one array with tickets of linked destinations &#8211; so you start from one city to another, than next and so &#8230; <a href="/2010/10/03/using-php-array_diff-in-algorithm-development/" class="more-link">Continue reading <span class="screen-reader-text">Using PHP&#8217;s array_diff in Algorithm Development</span> <span class="meta-nav">&#8594;</span></a><div class='yarpp-related-rss'>

Related posts:<ol>
<li><a href="/2010/08/31/php-what-is-more-powerful-than-list-perhaps-extract/" rel="bookmark" title="PHP: What is More Powerful Than list() &#8211; Perhaps extract()">PHP: What is More Powerful Than list() &#8211; Perhaps extract() </a></li>
<li><a href="/2011/10/19/thing-to-know-about-php-arrays/" rel="bookmark" title="Thing to Know About PHP Arrays">Thing to Know About PHP Arrays </a></li>
<li><a href="/2012/07/24/php-arrays-or-linked-lists/" rel="bookmark" title="PHP: Arrays or Linked Lists?">PHP: Arrays or Linked Lists? </a></li>
<li><a href="/2010/08/29/beginning-algorithm-complexity-and-estimation/" rel="bookmark" title="Beginning Algorithm Complexity and Estimation">Beginning Algorithm Complexity and Estimation </a></li>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<p><a title="PHP: array_diff" href="http://php.net/manual/en/function.array-diff.php" target="_blank">array_diff</a> can be really powerful. Once you&#8217;ve to find the different elements between two arrays you&#8217;ve to use array_diff. Here&#8217;s a case when you can use it while coding a simple algorithm.</p>
<h2>The Task</h2>
<p>You&#8217;ve one array with tickets of linked destinations &#8211; so you start from one city to another, than next and so on. Each element is an array with &#8220;from&#8221; and &#8220;to&#8221; destinations:</p>
<pre lang="php">
$inputTickets = array(
    0 => array('from' => 'barcelona', 'to' => 'madrid'),
    1 => array('from' => 'sofia', 'to' => 'paris'),
    2 => array('from' => 'madrid', 'to' => 'milano'),
    3 => array('from' => 'paris', 'to' => 'barcelona'),
    4 => array('from' => 'cupertino', 'to' => 'sofia'),
    5 => array('from' => 'milano', 'to' => 'valencia'),
    6 => array('from' => 'valencia', 'to' => 'nice'),
    7 => array('from' => 'mountain view', 'to' => 'cupertino'),
);
</pre>
<p>It&#8217;s easy to construct two arrays &#8211; the &#8220;from&#8221; destinations array and the &#8220;to&#8221; destinations array, and here the easiest way to get the starting point of the whole trip, because of the fact that these are linked tickets.</p>
<pre lang="php">
$fromDestinations = $toDestinations = array();

foreach ($inputTickets as $k => $v) {
    $fromDestinations[] = $v['from'];
    $toDestinations[]   = $v['to'];
}

// and finally get the starting point
$startPoint = array_diff($fromDestinations, $toDestinations);
</pre>
<h2>Conclusion</h2>
<p>Beside of knowing several algorithm techniques, there&#8217;s also need of knowing the language syntax and possibilities &#8211; in that case PHP&#8217;s</p>
<div class='yarpp-related-rss'>
<p>Related posts:<ol>
<li><a href="/2010/08/31/php-what-is-more-powerful-than-list-perhaps-extract/" rel="bookmark" title="PHP: What is More Powerful Than list() &#8211; Perhaps extract()">PHP: What is More Powerful Than list() &#8211; Perhaps extract() </a></li>
<li><a href="/2011/10/19/thing-to-know-about-php-arrays/" rel="bookmark" title="Thing to Know About PHP Arrays">Thing to Know About PHP Arrays </a></li>
<li><a href="/2012/07/24/php-arrays-or-linked-lists/" rel="bookmark" title="PHP: Arrays or Linked Lists?">PHP: Arrays or Linked Lists? </a></li>
<li><a href="/2010/08/29/beginning-algorithm-complexity-and-estimation/" rel="bookmark" title="Beginning Algorithm Complexity and Estimation">Beginning Algorithm Complexity and Estimation </a></li>
</ol></p>
</div>
]]></content:encoded>
			<wfw:commentRss>/2010/10/03/using-php-array_diff-in-algorithm-development/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>One Form &#8211; Multiple DB Records</title>
		<link>/2010/06/04/one-form-multiple-db-records/</link>
		<comments>/2010/06/04/one-form-multiple-db-records/#respond</comments>
		<pubDate>Fri, 04 Jun 2010 12:05:08 +0000</pubDate>
		<dc:creator><![CDATA[Stoimen]]></dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[web development]]></category>
		<category><![CDATA[Computing]]></category>
		<category><![CDATA[Control flow]]></category>
		<category><![CDATA[elegant solution]]></category>
		<category><![CDATA[Foreach]]></category>
		<category><![CDATA[html]]></category>
		<category><![CDATA[Iterator]]></category>
		<category><![CDATA[PHP programming language]]></category>
		<category><![CDATA[Technology/Internet]]></category>
		<category><![CDATA[web form]]></category>

		<guid isPermaLink="false">/?p=1584</guid>
		<description><![CDATA[I&#8217;ve the impression that even it&#8217;s a simple technique it remains quite misunderstood! What&#8217;s the Goal? You&#8217;ve a simple HTML form with several groups of form elements. Imagine the situation with title and link groups. You can have 1, 2 or more title/link pairs which you&#8217;d like to save in a database table, where perhaps &#8230; <a href="/2010/06/04/one-form-multiple-db-records/" class="more-link">Continue reading <span class="screen-reader-text">One Form &#8211; Multiple DB Records</span> <span class="meta-nav">&#8594;</span></a><div class='yarpp-related-rss'>

Related posts:<ol>
<li><a href="/2010/04/09/secure-forms-with-zend-framework/" rel="bookmark" title="Secure Forms with Zend Framework">Secure Forms with Zend Framework </a></li>
<li><a href="/2010/04/20/how-to-sanitize-user-input-in-php/" rel="bookmark" title="How to Sanitize User Input in PHP?">How to Sanitize User Input in PHP? </a></li>
<li><a href="/2010/09/10/automatically-upload-images-with-php-directly-from-the-uri/" rel="bookmark" title="Automatically Upload Images with PHP Directly from the URI">Automatically Upload Images with PHP Directly from the URI </a></li>
<li><a href="/2010/11/03/how-to-overcome-zend_cache_frontend_pages-problem-with-cookies/" rel="bookmark" title="How to Overcome Zend_Cache_Frontend_Page&#8217;s Problem with Cookies">How to Overcome Zend_Cache_Frontend_Page&#8217;s Problem with Cookies </a></li>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<p>I&#8217;ve the impression that even it&#8217;s a simple technique it remains quite misunderstood!</p>
<h2>What&#8217;s the Goal?</h2>
<p>You&#8217;ve a simple HTML form with several groups of form elements. Imagine the situation with title and link groups. You can have 1, 2 or more title/link pairs which you&#8217;d like to save in a database table, where perhaps there are only three columns &#8211; id, title, link.</p>
<h2>What is the Shortest Path to the Solution?</h2>
<p>In fact the task can be done by many ways, but there&#8217;s one really elegant solution. As it appears in many occasions PHP and HTML are born to work together!</p>
<h3>1. First Step</h3>
<p>Create your web form by simply modifying a bit the element names. Usually when you have an input you simply name it after the database column or something similar.</p>
<pre lang="html4strict">
<form method="POST">
	<input type="text" name="db_column_name" />
</form>
</pre>
<p>In reality PHP and HTML allows the name to be an array element, just like so:</p>
<pre lang="html4strict">
<form method="POST">
	<input type="text" name="link[0][title]" />
	<input type="text" name="link[0][url]" />
	
	<input type="text" name="link[1][title]" />
	<input type="text" name="link[1][url]" />
</form>
</pre>
<h3>2. Second Step</h3>
<p>Than all this comes in the _POST array in PHP, but formatted in an array manner, so you can simply foreach it!</p>
<pre lang="php">
<?php

foreach ($_POST['link'] as $link) {
	insert_into_db($link['title'], $link['url']);
}

?>
</pre>
<p>That is simply enough!</p>
<div class='yarpp-related-rss'>
<p>Related posts:<ol>
<li><a href="/2010/04/09/secure-forms-with-zend-framework/" rel="bookmark" title="Secure Forms with Zend Framework">Secure Forms with Zend Framework </a></li>
<li><a href="/2010/04/20/how-to-sanitize-user-input-in-php/" rel="bookmark" title="How to Sanitize User Input in PHP?">How to Sanitize User Input in PHP? </a></li>
<li><a href="/2010/09/10/automatically-upload-images-with-php-directly-from-the-uri/" rel="bookmark" title="Automatically Upload Images with PHP Directly from the URI">Automatically Upload Images with PHP Directly from the URI </a></li>
<li><a href="/2010/11/03/how-to-overcome-zend_cache_frontend_pages-problem-with-cookies/" rel="bookmark" title="How to Overcome Zend_Cache_Frontend_Page&#8217;s Problem with Cookies">How to Overcome Zend_Cache_Frontend_Page&#8217;s Problem with Cookies </a></li>
</ol></p>
</div>
]]></content:encoded>
			<wfw:commentRss>/2010/06/04/one-form-multiple-db-records/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>PHP if-else-endif Statements</title>
		<link>/2010/03/10/php-if-else-endif-statements/</link>
		<comments>/2010/03/10/php-if-else-endif-statements/#comments</comments>
		<pubDate>Wed, 10 Mar 2010 08:12:22 +0000</pubDate>
		<dc:creator><![CDATA[Stoimen]]></dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[Bracket]]></category>
		<category><![CDATA[Computer programming]]></category>
		<category><![CDATA[Computing]]></category>
		<category><![CDATA[Cross-platform software]]></category>
		<category><![CDATA[Curly bracket programming languages]]></category>
		<category><![CDATA[Foreach]]></category>
		<category><![CDATA[html]]></category>
		<category><![CDATA[PHP programming language]]></category>
		<category><![CDATA[Procedural programming languages]]></category>
		<category><![CDATA[Scripting languages]]></category>
		<category><![CDATA[Smarty]]></category>
		<category><![CDATA[Software engineering]]></category>
		<category><![CDATA[Technology/Internet]]></category>
		<category><![CDATA[template systems]]></category>
		<category><![CDATA[typical web developer]]></category>

		<guid isPermaLink="false">/?p=1221</guid>
		<description><![CDATA[PHP: if A typical web developer knows exactly how a PHP if statement looks like: if ( expression ) { // if the expression was true proceed here } else { // there was a false expression } HTML mess with PHP When it comes to merge PHP and HTML the things are becoming ugly. &#8230; <a href="/2010/03/10/php-if-else-endif-statements/" class="more-link">Continue reading <span class="screen-reader-text">PHP if-else-endif Statements</span> <span class="meta-nav">&#8594;</span></a><div class='yarpp-related-rss'>

Related posts:<ol>
<li><a href="/2012/04/26/php-strings-dont-need-quotes/" rel="bookmark" title="PHP Strings Don&#8217;t Need Quotes">PHP Strings Don&#8217;t Need Quotes </a></li>
<li><a href="/2010/05/19/php-associative-arrays-coding-style/" rel="bookmark" title="PHP Associative Arrays Coding Style">PHP Associative Arrays Coding Style </a></li>
<li><a href="/2010/05/25/php-coding-style-large-if-statements/" rel="bookmark" title="PHP Coding Style: Large IF Statements">PHP Coding Style: Large IF Statements </a></li>
<li><a href="/2010/02/07/javascript-optimization-optimizing-if-statements/" rel="bookmark" title="JavaScript optimization. Optimizing IF statements.">JavaScript optimization. Optimizing IF statements. </a></li>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<h2>PHP: if</h2>
<p>A typical web developer knows exactly how a PHP if statement looks like:</p>
<pre lang="php">   if ( expression ) {
      // if the expression was true proceed here
   } else {
      // there was a false expression
  }
</pre>
<h2>HTML mess with PHP</h2>
<p>When it comes to merge PHP and HTML the things are becoming ugly. Indeed most of the template systems as Smarty are improved and developed to overcome this issue, however when working with a native PHP code with no template system or with template system where the PHP code is allowed the things are really bad.</p>
<p>Let me show this in a breve example. Image you have to show different formatted HTML depending on a PHP expression. Something like that</p>
<pre lang="php">
<?php if (expression) { ?>
<div class="message">OK. Your registration is successful</div>
<?php } else { ?>
<div class="error">Something went wrong! Please try again later! </div>
<?php } ?>
</pre>
<p>Now you can see how difficult to maintain this code is when it doesn&#8217;t make use of only one code of HTML markup. Imaging you&#8217;ve to print differently formatted tables! Indeed the PHP curly brackets are different to follow.</p>
<h2>PHP: the different IF syntax</h2>
<p>So there is a PHP syntax that tries to help you manage this. You can write more human readable code like this:</p>
<pre lang="php">
<?php if ( expression ) : ?>
<div>message goes here</div>
<?php endif ?>
</pre>
<p>Thus you get the ENDIF instead of only one curly bracket. That&#8217;s indeed readable enough. In fact you can use this syntax with any conditional or loop statement in PHP:</p>
<pre lang="php">
<?php foreach($array as $key => $val) : ?>
<div class="message"><?php echo $val ?></div><br />
<?php endforeach ?>
</pre>
<p>To return in the previous example the code above should be transformed in that:</p>
<pre lang="php">
<?php if ( expression ) : ?>
<div class="message">some message here!</div>
<?php else : ?>
<div class="error">some error here!</div>
<?php endif ?>
</pre>
<div class='yarpp-related-rss'>
<p>Related posts:<ol>
<li><a href="/2012/04/26/php-strings-dont-need-quotes/" rel="bookmark" title="PHP Strings Don&#8217;t Need Quotes">PHP Strings Don&#8217;t Need Quotes </a></li>
<li><a href="/2010/05/19/php-associative-arrays-coding-style/" rel="bookmark" title="PHP Associative Arrays Coding Style">PHP Associative Arrays Coding Style </a></li>
<li><a href="/2010/05/25/php-coding-style-large-if-statements/" rel="bookmark" title="PHP Coding Style: Large IF Statements">PHP Coding Style: Large IF Statements </a></li>
<li><a href="/2010/02/07/javascript-optimization-optimizing-if-statements/" rel="bookmark" title="JavaScript optimization. Optimizing IF statements.">JavaScript optimization. Optimizing IF statements. </a></li>
</ol></p>
</div>
]]></content:encoded>
			<wfw:commentRss>/2010/03/10/php-if-else-endif-statements/feed/</wfw:commentRss>
		<slash:comments>13</slash:comments>
		</item>
	</channel>
</rss>
