<?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>Computer programming &#8211; stoimen&#039;s web log</title>
	<atom:link href="/tag/computer-programming/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 Strings Don&#8217;t Need Quotes</title>
		<link>/2012/04/26/php-strings-dont-need-quotes/</link>
		<comments>/2012/04/26/php-strings-dont-need-quotes/#comments</comments>
		<pubDate>Thu, 26 Apr 2012 13:52:53 +0000</pubDate>
		<dc:creator><![CDATA[Stoimen]]></dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[C]]></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[PHP interpreter]]></category>
		<category><![CDATA[PHP programming language]]></category>
		<category><![CDATA[Procedural programming languages]]></category>
		<category><![CDATA[Programming language]]></category>
		<category><![CDATA[Scripting languages]]></category>
		<category><![CDATA[Social Issues]]></category>
		<category><![CDATA[Software engineering]]></category>
		<category><![CDATA[String]]></category>

		<guid isPermaLink="false">/?p=3017</guid>
		<description><![CDATA[I bet you didn&#8217;t know that PHP strings don&#8217;t need quotes! Indeed PHP developers work with strings with either single or double quotes, but actually in some cases you don&#8217;t need them. PHP by Book Here&#8217;s how PHP developer declare a string, which is something very common in any programming language. $my_var = 'hello world'; &#8230; <a href="/2012/04/26/php-strings-dont-need-quotes/" class="more-link">Continue reading <span class="screen-reader-text">PHP Strings Don&#8217;t Need Quotes</span> <span class="meta-nav">&#8594;</span></a><div class='yarpp-related-rss'>

Related posts:<ol>
<li><a href="/2011/07/12/a-javascript-trick-you-should-know/" rel="bookmark" title="A JavaScript Trick You Should Know">A JavaScript Trick You Should Know </a></li>
<li><a href="/2010/03/10/php-if-else-endif-statements/" rel="bookmark" title="PHP if-else-endif Statements">PHP if-else-endif Statements </a></li>
<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/10/json-and-zend-framework-zend_json/" rel="bookmark" title="JSON and Zend Framework? &#8211; Zend_Json">JSON and Zend Framework? &#8211; Zend_Json </a></li>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<p>I bet you didn&#8217;t know that PHP strings don&#8217;t need quotes! Indeed PHP developers work with strings with either single or double quotes, but actually in some cases you don&#8217;t need them.</p>
<h2>PHP by Book</h2>
<p>Here&#8217;s how PHP developer declare a string, which is something very common in any programming language.</p>
<pre lang="PHP">
$my_var = 'hello world';
// or
$my_var = "hello world";
</pre>
<h2>PHP Tricks</h2>
<p>What if you do the following:</p>
<pre lang="PHP">
echo hello;
</pre>
<p>That appears to be correct &#8230; Well, it&#8217;s not absolutely correct. You&#8217;ll be &#8220;noticed&#8221;.</p>
<pre lang="PHP">
// Notice: Use of undefined constant hello
echo hello;
</pre>
<p>However if you disable error reporting, the code will be completely fine.</p>
<pre lang="PHP">
error_reporting(0);

// no problem now
echo hello;
</pre>
<h2>Variations</h2>
<p>What follows from the thing above is that you can use strings without quotes:</p>
<pre lang="PHP">
// hello
echo hello;

// hello world (concatenated)
echo hello . ' world';

// helloworld
echo hello . world;
</pre>
<p>However you can&#8217;t have spaces and most of the &#8220;special&#8221; symbols.</p>
<pre lang="PHP">
// syntax error
echo hello world;

// syntax error
echo hello!;
</pre>
<h2>Final Words</h2>
<p>Although you can do this in PHP, that is completely wrong. The code becomes more difficult to read and understand. In the second place you can miss a $ sign in front of a variable declaration and thus the PHP interpreter will assume this is a string. So disable error reporting isn&#8217;t so great sometimes.</p>
<div class='yarpp-related-rss'>
<p>Related posts:<ol>
<li><a href="/2011/07/12/a-javascript-trick-you-should-know/" rel="bookmark" title="A JavaScript Trick You Should Know">A JavaScript Trick You Should Know </a></li>
<li><a href="/2010/03/10/php-if-else-endif-statements/" rel="bookmark" title="PHP if-else-endif Statements">PHP if-else-endif Statements </a></li>
<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/10/json-and-zend-framework-zend_json/" rel="bookmark" title="JSON and Zend Framework? &#8211; Zend_Json">JSON and Zend Framework? &#8211; Zend_Json </a></li>
</ol></p>
</div>
]]></content:encoded>
			<wfw:commentRss>/2012/04/26/php-strings-dont-need-quotes/feed/</wfw:commentRss>
		<slash:comments>15</slash:comments>
		</item>
		<item>
		<title>Computer Algorithms: Boyer-Moore String Searching</title>
		<link>/2012/04/17/computer-algorithms-boyer-moore-string-search-and-matching/</link>
		<comments>/2012/04/17/computer-algorithms-boyer-moore-string-search-and-matching/#comments</comments>
		<pubDate>Tue, 17 Apr 2012 08:24:46 +0000</pubDate>
		<dc:creator><![CDATA[Stoimen]]></dc:creator>
				<category><![CDATA[algorithms]]></category>
		<category><![CDATA[Boyer–Moore string search algorithm]]></category>
		<category><![CDATA[Boyer–Moore–Horspool algorithm]]></category>
		<category><![CDATA[Computer programming]]></category>
		<category><![CDATA[Computer science]]></category>
		<category><![CDATA[Computing]]></category>
		<category><![CDATA[J Strother Moore]]></category>
		<category><![CDATA[Morris-Pratt algorithm]]></category>
		<category><![CDATA[natural language search]]></category>
		<category><![CDATA[pattern forward]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Rabin-Karp algorithm]]></category>
		<category><![CDATA[Rabin-Karp string search algorithm]]></category>
		<category><![CDATA[Robert S. Boyer]]></category>
		<category><![CDATA[search]]></category>
		<category><![CDATA[search algorithms]]></category>
		<category><![CDATA[String searching algorithm]]></category>
		<category><![CDATA[string searching algorithms]]></category>
		<category><![CDATA[Strlen]]></category>
		<category><![CDATA[Substring]]></category>

		<guid isPermaLink="false">/?p=3049</guid>
		<description><![CDATA[Introduction Have you ever asked yourself which is the algorithm used to find a word after clicking Ctrl+F and typing something? Well I guess you know the answer from the title, but in this article you’ll find out how exactly this is done. As we saw from the Morris-Pratt string searching we don’t need to &#8230; <a href="/2012/04/17/computer-algorithms-boyer-moore-string-search-and-matching/" class="more-link">Continue reading <span class="screen-reader-text">Computer Algorithms: Boyer-Moore String Searching</span> <span class="meta-nav">&#8594;</span></a><div class='yarpp-related-rss'>

Related posts:<ol>
<li><a href="/2012/04/09/computer-algorithms-morris-pratt-string-searching/" rel="bookmark" title="Computer Algorithms: Morris-Pratt String Searching">Computer Algorithms: Morris-Pratt String Searching </a></li>
<li><a href="/2012/04/02/computer-algorithms-rabin-karp-string-searching/" rel="bookmark" title="Computer Algorithms: Rabin-Karp String Searching">Computer Algorithms: Rabin-Karp String Searching </a></li>
<li><a href="/2012/03/27/computer-algorithms-brute-force-string-matching/" rel="bookmark" title="Computer Algorithms: Brute Force String Matching">Computer Algorithms: Brute Force String Matching </a></li>
<li><a href="/2011/11/24/computer-algorithms-sequential-search/" rel="bookmark" title="Computer Algorithms: Sequential Search">Computer Algorithms: Sequential Search </a></li>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<h2>Introduction</h2>
<p>Have you ever asked yourself which is the algorithm used to find a word after clicking Ctrl+F and typing something? Well I guess you know the answer from the title, but in this article you’ll find out how exactly this is done.</p>
<p>As we saw from the <a href="/2012/04/09/computer-algorithms-morris-pratt-string-searching/" title="Computer Algorithms: Morris-Pratt String Searching">Morris-Pratt string searching</a> we don’t need to compare the text and the pattern character by character. Some comparisons can be skipped in order to improve the performance of the string searching. Indeed the <a href="/2012/03/27/computer-algorithms-brute-force-string-matching/" title="Computer Algorithms: Brute Force String Matching">brute force string searching</a> and the <a href="/2012/04/02/computer-algorithms-rabin-karp-string-searching/" title="Computer Algorithms: Rabin-Karp String Searching">Rabin-Karp algorithm</a> are quite slow only because they compare the pattern and the text character by character.</p>
<p>In the other hand the Morris-Pratt algorithm is a very good improvement of the brute force string searching, but the question remains. Is there any algorithm that is faster than Morris-Pratt &#8211; is there any way to skip more comparisons and to move the pattern faster.</p>
<p>It’s clear that if we have to find whether a single character is contained into a text we need at least &#8220;n&#8221; steps, where n is the length of the text. Once we have to find whether a pattern with the length of &#8220;m&#8221; is contained into a text with length of &#8220;n&#8221; the case is getting a little more complex.</p>
<p>However the answer is that there is such algorithm that is faster and more suitable than Morris-Pratt. This is the Boyer-Moore string searching.</p>
<h2>Overview</h2>
<p>Boyer-Moore is an algorithm that improves the performance of pattern searching into a text by considering some observations. It is defined in 1977 by <a href="http://en.wikipedia.org/wiki/Robert_S._Boyer" title="Robert S. Boyer" target="_blank">Robert S. Boyer</a> and <a href="http://en.wikipedia.org/wiki/J_Strother_Moore" title="J Strother Moore" target="_blank">J Strother Moore</a> and it consist of some specific features. </p>
<p>First of all this algorithm starts comparing the pattern from the leftmost part of text and moves it to the right, as on the picture below.</p>
<p><figure id="attachment_3059" style="width: 618px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/04/Boyer-MooreShiftingDirection.png"><img src="/wp-content/uploads/2012/04/Boyer-MooreShiftingDirection.png" alt="Boyer-Moore Shifting Direction" title="Boyer-Moore Shifting Direction" width="618" height="153" class="size-full wp-image-3059" srcset="/wp-content/uploads/2012/04/Boyer-MooreShiftingDirection.png 618w, /wp-content/uploads/2012/04/Boyer-MooreShiftingDirection-300x74.png 300w" sizes="(max-width: 618px) 100vw, 618px" /></a><figcaption class="wp-caption-text">In Boyer-Moore the pattern is shifted from left to right!</figcaption></figure><span id="more-3049"></span></p>
<p>Unlike other string searching algorithms though, Boyer-Moore compares the pattern against a possible match from right to left as shown below.</p>
<figure id="attachment_3066" style="width: 622px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/04/Boyer-MooreComparisonModel.png"><img src="/wp-content/uploads/2012/04/Boyer-MooreComparisonModel.png" alt="Boyer-Moore Comparison Model" title="Boyer-Moore Comparison Model" width="622" height="169" class="size-full wp-image-3066" srcset="/wp-content/uploads/2012/04/Boyer-MooreComparisonModel.png 622w, /wp-content/uploads/2012/04/Boyer-MooreComparisonModel-300x81.png 300w" sizes="(max-width: 622px) 100vw, 622px" /></a><figcaption class="wp-caption-text">Unlike other algorithms the letters of the pattern are compared from right to left!</figcaption></figure>
<p>The main idea of Boyer-Moore in order to improve the performance are some observations of the pattern. In the terminology of this algorithm they are called good-suffix and bad-character shifts. Let’s see by the following examples what they are standing for.</p>
<h3>Good-suffix Shifts</h3>
<p>Just like the Morris-Pratt algorithm we start to compare the pattern against some portion of the text where a possible match will occur. In Boyer-Moore as I said this is done from the rightmost letter of the pattern. After some characters have matched we find a mismatch.</p>
<figure id="attachment_3065" style="width: 622px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/04/Boyer-MooreAMismatch.png"><img src="/wp-content/uploads/2012/04/Boyer-MooreAMismatch.png" alt="Boyer-Moore a Mismatch" title="Boyer-Moore a Mismatch" width="622" height="214" class="size-full wp-image-3065" srcset="/wp-content/uploads/2012/04/Boyer-MooreAMismatch.png 622w, /wp-content/uploads/2012/04/Boyer-MooreAMismatch-300x103.png 300w" sizes="(max-width: 622px) 100vw, 622px" /></a><figcaption class="wp-caption-text"> </figcaption></figure>
<p>So how can we move the pattern to the right in order to skip unusual comparisons. To answer this question we need to explore the pattern. Let’s say there is a portion of the pattern that is repeated inside the pattern itself, like it is shown on the picture below.</p>
<figure id="attachment_3062" style="width: 622px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/04/Boyer-MooreGood-suffixShift1.png"><img src="/wp-content/uploads/2012/04/Boyer-MooreGood-suffixShift1.png" alt="Boyer-Moore Good-suffix Shift 1" title="Boyer-Moore Good-suffix Shift 1" width="622" height="195" class="size-full wp-image-3062" srcset="/wp-content/uploads/2012/04/Boyer-MooreGood-suffixShift1.png 622w, /wp-content/uploads/2012/04/Boyer-MooreGood-suffixShift1-300x94.png 300w" sizes="(max-width: 622px) 100vw, 622px" /></a><figcaption class="wp-caption-text">The pattern may consist of repeating portions of characters!</figcaption></figure>
<p>In this case we must move the pattern thus the repeated portion must now align with its first occurrence in the pattern.</p>
<p>A variation of this case is when the portion from the pattern A overlaps with another portion that consists of the same characters.</p>
<figure id="attachment_3061" style="width: 622px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/04/Boyer-MooreGoodSuffixShift2.png"><img src="/wp-content/uploads/2012/04/Boyer-MooreGoodSuffixShift2.png" alt="Boyer-Moore Good Suffix Shift 2" title="Boyer-Moore Good Suffix Shift 2" width="622" height="195" class="size-full wp-image-3061" srcset="/wp-content/uploads/2012/04/Boyer-MooreGoodSuffixShift2.png 622w, /wp-content/uploads/2012/04/Boyer-MooreGoodSuffixShift2-300x94.png 300w" sizes="(max-width: 622px) 100vw, 622px" /></a><figcaption class="wp-caption-text">Sometimes these portions may overlap!</figcaption></figure>
<p>Yet again the shift must align the second portion with its first occurrence. </p>
<p>Finally only a portion of A, let’s say &#8220;B&#8221;, can happen to occur in the very beginning of the pattern, as on the diagram below.</p>
<figure id="attachment_3060" style="width: 622px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/04/Boyer-MooreGoodSuffixShift3.png"><img src="/wp-content/uploads/2012/04/Boyer-MooreGoodSuffixShift3.png" alt="Boyer-Moore Good Suffix Shift 3" title="Boyer-Moore Good Suffix Shift 3" width="622" height="195" class="size-full wp-image-3060" srcset="/wp-content/uploads/2012/04/Boyer-MooreGoodSuffixShift3.png 622w, /wp-content/uploads/2012/04/Boyer-MooreGoodSuffixShift3-300x94.png 300w" sizes="(max-width: 622px) 100vw, 622px" /></a><figcaption class="wp-caption-text">Only a sub-string of the pattern may re-occur at its front!</figcaption></figure>
<p>Now we must align the left end of the pattern with the rightmost occurrence of &#8220;B&#8221;.</p>
<h3>Bad Character Shifts</h3>
<p>Beside the good-suffix shifts the Boyer-Moore algorithm make use of the so called bad-character shifts. In case of a mismatch we can skip comparisons in case the character in the text doesn’t happen to appear in the pattern. To become clearer let’s see the following examples.</p>
<figure id="attachment_3064" style="width: 623px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/04/Boyer-MooreBadCharacter1.png"><img src="/wp-content/uploads/2012/04/Boyer-MooreBadCharacter1.png" alt="Boyer-Moore Bad Character 1" title="Boyer-Moore Bad Character 1" width="623" height="237" class="size-full wp-image-3064" srcset="/wp-content/uploads/2012/04/Boyer-MooreBadCharacter1.png 623w, /wp-content/uploads/2012/04/Boyer-MooreBadCharacter1-300x114.png 300w" sizes="(max-width: 623px) 100vw, 623px" /></a><figcaption class="wp-caption-text">If the mismatched letter of the text appears in the pattern only in its front we can align it easily!</figcaption></figure>
<p>In the picture above we see that the mismatched character &#8220;B&#8221; from the text appears only in the beginning of the pattern. Thus we can simply shift the pattern to the right and align both characters B, skipping comparisons. An even better case is described by the following diagram where the mismatched letter isn’t contained into the pattern at all. Then we can shift forward the whole pattern.</p>
<figure id="attachment_3063" style="width: 623px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/04/Boyer-MooreBadCharacter2.png"><img src="/wp-content/uploads/2012/04/Boyer-MooreBadCharacter2.png" alt="Boyer-Moore Bad Character 2" title="Boyer-Moore Bad Character 2" width="623" height="237" class="size-full wp-image-3063" srcset="/wp-content/uploads/2012/04/Boyer-MooreBadCharacter2.png 623w, /wp-content/uploads/2012/04/Boyer-MooreBadCharacter2-300x114.png 300w" sizes="(max-width: 623px) 100vw, 623px" /></a><figcaption class="wp-caption-text">In case the mismatched letter isn&#039;t contained into the pattern we move forward the pattern!</figcaption></figure>
<h3>Maximum of Good-suffix and Bad-Character shifts</h3>
<p>Boyer-Moore needs both good-suffix and bad-character shifts in order to speed up searching performance. After a mismatch the maximum of both is considered in order to move the pattern to the right.</p>
<h2>Complexity</h2>
<p>It&#8217;s clear that Boyer-Moore is faster than Morris-Pratt, but actually its worst-case complexity is O(n+m). The thing is that in natural language search Boyer-Moore does pretty well.</p>
<figure id="attachment_3073" style="width: 600px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/04/Boyer-Moore-Complexity.png"><img src="/wp-content/uploads/2012/04/Boyer-Moore-Complexity.png" alt="Boyer-Moore Complexity" title="Boyer-Moore Complexity" width="600" height="371" class="size-full wp-image-3073" srcset="/wp-content/uploads/2012/04/Boyer-Moore-Complexity.png 600w, /wp-content/uploads/2012/04/Boyer-Moore-Complexity-300x185.png 300w" sizes="(max-width: 600px) 100vw, 600px" /></a><figcaption class="wp-caption-text">Worst-case scenario of Boyer-Moore - O(m+n)</figcaption></figure>
<h2>Implementation</h2>
<p>Finally let’s see the implementation in <a href="/category/php/" title="PHP on stoimen.com">PHP</a>, which can be easily &#8220;transcribed&#8221; into any other programming language. The only thing we need is the structures for bad-character shifts and good-suffixes shifts.</p>
<pre lang="PHP">
<?php

/**
 * Pattern we're searching for
 *
 * @var string
 */
$pattern = 'gloria';

/**
 * The text we're searching in
 *
 * @var string
 */
$text = 'Sic transit gloria mundi, non transit gloria Gundi!';

/**
 * Calculates the suffixes for a given pattern
 *
 * @param string $pattern
 * @param array  $suffixes
 */
function suffixes($pattern, &#038;$suffixes)
{
   $m = strlen($pattern);

   $suffixes[$m - 1] = $m;
   $g = $m - 1;

   for ($i = $m - 2; $i >= 0; --$i) {
      if ($i > $g && $suffixes[$i + $m - 1 - $f] < $i - $g) {
         $suffixes[$i] = $suffixes[$i + $m - 1 - $f];
      } else {
         if ($i < $g) {
            $g = $i;
         }
         $f = $i;
         	
         while ($g >= 0 && $pattern[$g] == $pattern[$g + $m - 1 - $f]) {
            $g--;
         }
         $suffixes[$i] = $f - $g;
      }
   }
}

/**
 * Fills in the array of bad characters.
 *
 * @param string $pattern
 * @param array  $badChars
 */
function badCharacters($pattern, &$badChars)
{
   $m = strlen($pattern);

   for ($i = 0; $i < $m - 1; ++$i) {
      $badChars[$pattern{$i}] = $m - $i - 1;
   }
}

/**
 * Fills in the array of good suffixes
 *
 * @param string $pattern
 * @param array  $goodSuffixes
 */
function goodSuffixes($pattern, &#038;$goodSuffixes)
{
   $m 		= strlen($pattern);
   $suff 	= array();

   suffixes($pattern, $suff);

   for ($i = 0; $i < $m; $i++) {
      $goodSuffixes[$i] = $m;
   }

   for ($i = $m - 1; $i >= 0; $i--) {
      if ($suff[$i] == $i + 1) {
         for ($j = 0; $j < $m - $i - 1; $j++) {
            if ($goodSuffixes[$j] == $m) {
               $goodSuffixes[$j] = $m - $i - 1;
            }
         }
      }
   }

   for ($i = 0; $i < $m - 2; $i++) {
      $goodSuffixes[$m - 1 - $suff[$i]] = $m - $i - 1;
   }
}

/**
 * Performs a search of the pattern into a given text
 *
 * @param string $pattern
 * @param string $text
 */
function boyer_moore($pattern, $text)
{
   $n = strlen($text);
   $m = strlen($pattern);

   $goodSuffixes 	= array();
   $badCharacters 	= array();

   goodSuffixes($pattern, &#038;$goodSuffixes);
   badCharacters($pattern, &#038;$badCharacters);

   $j = 0;
   while ($j < $n - $m) {
      for ($i = $m - 1; $i >= 0 && $pattern[$i] == $text[$i + $j]; $i--);
      if ($i < 0) {
         // note that if the substring occurs more
         // than once into the text, the algorithm will
         // print out each position of the substring
         echo $j;
         $j += $goodSuffixes[0];
      } else {
         $j += max($goodSuffixes[$i], $badCharacters[$text[$i + $j]] - $m + $i + 1);
      }
   }
}

// search using Boyer-Moore
// will return 12 and 38
boyer_moore($pattern, $text);
</pre>
<h2>Application</h2>
<p>Boyer-Moore is one of the most used string searching algorithm in practice. It is intuitively clear where it can be useful, but yet again I’ll say only that this algorithm is considered as the mostly used in practice for search and replace operations in text editors.</p>
<figure id="attachment_3068" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/04/Boyer-MooreApplication.png"><img src="/wp-content/uploads/2012/04/Boyer-MooreApplication.png" alt="Boyer-Moore Application" title="Boyer-Moore Application" width="620" height="399" class="size-full wp-image-3068" srcset="/wp-content/uploads/2012/04/Boyer-MooreApplication.png 620w, /wp-content/uploads/2012/04/Boyer-MooreApplication-300x193.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text"> </figcaption></figure>
<div class='yarpp-related-rss'>
<p>Related posts:<ol>
<li><a href="/2012/04/09/computer-algorithms-morris-pratt-string-searching/" rel="bookmark" title="Computer Algorithms: Morris-Pratt String Searching">Computer Algorithms: Morris-Pratt String Searching </a></li>
<li><a href="/2012/04/02/computer-algorithms-rabin-karp-string-searching/" rel="bookmark" title="Computer Algorithms: Rabin-Karp String Searching">Computer Algorithms: Rabin-Karp String Searching </a></li>
<li><a href="/2012/03/27/computer-algorithms-brute-force-string-matching/" rel="bookmark" title="Computer Algorithms: Brute Force String Matching">Computer Algorithms: Brute Force String Matching </a></li>
<li><a href="/2011/11/24/computer-algorithms-sequential-search/" rel="bookmark" title="Computer Algorithms: Sequential Search">Computer Algorithms: Sequential Search </a></li>
</ol></p>
</div>
]]></content:encoded>
			<wfw:commentRss>/2012/04/17/computer-algorithms-boyer-moore-string-search-and-matching/feed/</wfw:commentRss>
		<slash:comments>21</slash:comments>
		</item>
		<item>
		<title>Computer Algorithms: Morris-Pratt String Searching</title>
		<link>/2012/04/09/computer-algorithms-morris-pratt-string-searching/</link>
		<comments>/2012/04/09/computer-algorithms-morris-pratt-string-searching/#comments</comments>
		<pubDate>Mon, 09 Apr 2012 19:41:05 +0000</pubDate>
		<dc:creator><![CDATA[Stoimen]]></dc:creator>
				<category><![CDATA[algorithms]]></category>
		<category><![CDATA[Applied mathematics]]></category>
		<category><![CDATA[Boyer–Moore string search algorithm]]></category>
		<category><![CDATA[Brute-force search]]></category>
		<category><![CDATA[Complexity This algorithm]]></category>
		<category><![CDATA[Computer programming]]></category>
		<category><![CDATA[Computer science]]></category>
		<category><![CDATA[faster string searching algorithms]]></category>
		<category><![CDATA[James H. Morris]]></category>
		<category><![CDATA[Knuth–Morris–Pratt algorithm]]></category>
		<category><![CDATA[Lorem ipsum]]></category>
		<category><![CDATA[Morris-Pratt algorithm]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Rabin]]></category>
		<category><![CDATA[Rabin-Karp algorithm]]></category>
		<category><![CDATA[Rabin-Karp string search algorithm]]></category>
		<category><![CDATA[search algorithms]]></category>
		<category><![CDATA[String searching algorithm]]></category>
		<category><![CDATA[Vaughan Pratt]]></category>

		<guid isPermaLink="false">/?p=3019</guid>
		<description><![CDATA[Introduction We saw that neither brute force string searching nor Rabin-Karp string searching are effective. However in order to improve some algorithm, first we need to understand its principles in detail. We know already that brute force string matching is slow and we tried to improve it somehow by using a hash function in the &#8230; <a href="/2012/04/09/computer-algorithms-morris-pratt-string-searching/" class="more-link">Continue reading <span class="screen-reader-text">Computer Algorithms: Morris-Pratt String Searching</span> <span class="meta-nav">&#8594;</span></a><div class='yarpp-related-rss'>

Related posts:<ol>
<li><a href="/2012/04/17/computer-algorithms-boyer-moore-string-search-and-matching/" rel="bookmark" title="Computer Algorithms: Boyer-Moore String Searching">Computer Algorithms: Boyer-Moore String Searching </a></li>
<li><a href="/2012/04/02/computer-algorithms-rabin-karp-string-searching/" rel="bookmark" title="Computer Algorithms: Rabin-Karp String Searching">Computer Algorithms: Rabin-Karp String Searching </a></li>
<li><a href="/2012/03/27/computer-algorithms-brute-force-string-matching/" rel="bookmark" title="Computer Algorithms: Brute Force String Matching">Computer Algorithms: Brute Force String Matching </a></li>
<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>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<h2>Introduction</h2>
<p>We saw that neither <a href="/2012/03/27/computer-algorithms-brute-force-string-matching/" title="Computer Algorithms: Brute Force String Matching">brute force string searching</a> nor <a href="/2012/04/02/computer-algorithms-rabin-karp-string-searching/" title="Computer Algorithms: Rabin-Karp String Searching">Rabin-Karp string searching</a> are effective. However in order to improve some algorithm, first we need to understand its principles in detail. We know already that brute force string matching is slow and we tried to improve it somehow by using a hash function in the Rabin-Karp algorithm. The problem is that Rabin-Karp has the same complexity as brute force string matching, which is O(mn).</p>
<p>Obviously we need a different approach, but to come with a different approach let’s see what’s wrong with brute force string searching. Indeed by taking a closer look at its principles we can answer the question. </p>
<p>In brute force matching we checked each character of the text with the first character of the pattern. In case of a match we shifted the comparison between the second character of the pattern and the next character of the text. The problem is that in case of a mismatch we must go several positions back in the text. Well in fact this technique can’t be optimized. </p>
<p><figure id="attachment_3025" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/04/Morris-Pratt-brute-force-string-matching.png"><img src="/wp-content/uploads/2012/04/Morris-Pratt-brute-force-string-matching.png" alt="Morris-Pratt brute force string matching" title="Morris-Pratt brute force string matching" width="620" height="360" class="size-full wp-image-3025" srcset="/wp-content/uploads/2012/04/Morris-Pratt-brute-force-string-matching.png 620w, /wp-content/uploads/2012/04/Morris-Pratt-brute-force-string-matching-300x174.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">In brute force string matching in case of a mismatch we go back and we compare characters that has been compared already!</figcaption></figure><span id="more-3019"></span></p>
<p>As you can see on the picture above the problem is that once there is a mismatch we must rollback and start comparing from a position in the text that has been explored already. In our case we have checked the first, second, third and fourth letters, where there is a mismatch between the pattern and the text and then &#8230; we go back and start comparing from the second letter of the text.</p>
<p>This is completely useless, because we already know that the pattern begins with the letter “a” and no such letter happens to be between positions 1 and 3. So how can we improve this redundancy?</p>
<h2>Overview</h2>
<p>The answer of the question came to <a href="http://en.wikipedia.org/wiki/James_H._Morris" title="James H. Morris" target="_blank">James H. Morris</a> and <a href="http://en.wikipedia.org/wiki/Vaughan_Pratt" title="Vaughan Pratt" target="_blank">Vaughan Pratt</a> in 1977 when they described their algorithm, which by skipping lots of useless comparisons is more effective than brute force string matching. Let’s see it in detail. The only thing is to use the information gathered during the comparisons of the pattern and a possible match, as on the picture below.</p>
<figure id="attachment_3029" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/04/Morris-Pratt-basic-principles.png"><img src="/wp-content/uploads/2012/04/Morris-Pratt-basic-principles.png" alt="Morris-Pratt basic principles" title="Morris-Pratt basic principles" width="620" height="483" class="size-full wp-image-3029" srcset="/wp-content/uploads/2012/04/Morris-Pratt-basic-principles.png 620w, /wp-content/uploads/2012/04/Morris-Pratt-basic-principles-300x233.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">Morris-Pratt skips some comparisons by moving ahead to the next possible position of a match!</figcaption></figure>
<p>To do that first we have to preprocess the pattern in order to get possible positions for next matches. Thus after we start to find a possible match in case of a mismatch we’ll know exactly where we should jump in order to skip unusual comparisons.</p>
<h3>Generating the Table of Next Positions</h3>
<p>This is the tricky part in Morris-Pratt and that is how this algorithm overcomes the disadvantages of brute force string searching. Let&#8217;s see some pictures.</p>
<figure id="attachment_3044" style="width: 623px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/04/Morris-Pratt-with-no-repeating-letters-in-the-pattern.png"><img src="/wp-content/uploads/2012/04/Morris-Pratt-with-no-repeating-letters-in-the-pattern.png" alt="Morris-Pratt with no repeating letters in the pattern" title="Morris-Pratt with no repeating letters in the pattern" width="623" height="361" class="size-full wp-image-3044" srcset="/wp-content/uploads/2012/04/Morris-Pratt-with-no-repeating-letters-in-the-pattern.png 623w, /wp-content/uploads/2012/04/Morris-Pratt-with-no-repeating-letters-in-the-pattern-300x173.png 300w" sizes="(max-width: 623px) 100vw, 623px" /></a><figcaption class="wp-caption-text">It is clear that if the pattern consists only of different letters in case of a mismatch we should start comparing the next character of the text with the first character of the pattern!</figcaption></figure>
<p>However in case of repeating character in the pattern if we have a mismatch after that character a possible match must begin from this repeating character, as on the picture bellow.</p>
<figure id="attachment_3045" style="width: 622px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/04/Morris-Pratt-with-one-repeating-letter-in-the-pattern.png"><img src="/wp-content/uploads/2012/04/Morris-Pratt-with-one-repeating-letter-in-the-pattern.png" alt="Morris-Pratt with one repeating letter in the pattern" title="Morris-Pratt with one repeating letter in the pattern" width="622" height="404" class="size-full wp-image-3045" srcset="/wp-content/uploads/2012/04/Morris-Pratt-with-one-repeating-letter-in-the-pattern.png 622w, /wp-content/uploads/2012/04/Morris-Pratt-with-one-repeating-letter-in-the-pattern-300x194.png 300w" sizes="(max-width: 622px) 100vw, 622px" /></a><figcaption class="wp-caption-text">The next table is slightly different if the pattern has repeating character! </figcaption></figure>
<p>Finally if there are more than one repeating character in the text the &#8220;next&#8221; table will consist show their position.</p>
<figure id="attachment_3046" style="width: 622px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/04/Morris-Pratt-more-than-one-repeating-letter-in-the-pattern.png"><img src="/wp-content/uploads/2012/04/Morris-Pratt-more-than-one-repeating-letter-in-the-pattern.png" alt="Morris-Pratt more than one repeating letter in the pattern" title="Morris-Pratt more than one repeating letter in the pattern" width="622" height="461" class="size-full wp-image-3046" srcset="/wp-content/uploads/2012/04/Morris-Pratt-more-than-one-repeating-letter-in-the-pattern.png 622w, /wp-content/uploads/2012/04/Morris-Pratt-more-than-one-repeating-letter-in-the-pattern-300x222.png 300w" sizes="(max-width: 622px) 100vw, 622px" /></a><figcaption class="wp-caption-text">The next table contains the positions of repeating letters!</figcaption></figure>
<p>After we have this table of possible “next” positions we can start exploring the text for our pattern.</p>
<figure id="attachment_3027" style="width: 622px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/04/Morris-Pratt.png"><img src="/wp-content/uploads/2012/04/Morris-Pratt.png" alt="Morris-Pratt" title="Morris-Pratt" width="622" height="550" class="size-full wp-image-3027" srcset="/wp-content/uploads/2012/04/Morris-Pratt.png 622w, /wp-content/uploads/2012/04/Morris-Pratt-300x265.png 300w" sizes="(max-width: 622px) 100vw, 622px" /></a><figcaption class="wp-caption-text"> </figcaption></figure>
<h2>Implementation</h2>
<p>Implementing Morris-Pratt isn’t difficult. First we have to preprocess the pattern and then perform the search. The following <a href="/category/php/" title="PHP on stoimen.com">PHP</a> code shows you how to do that.</p>
<pre lang="PHP">
/**
 * Pattern
 * 
 * @var string
 */
$pattern = 'mollis';

/**
 * Text to search
 * 
 * @var string
 */
$text = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque eleifend nisi viverra ipsum elementum porttitor quis at justo. Aliquam ligula felis, dignissim sit amet lobortis eget, lacinia ac augue. Quisque nec est elit, nec ultricies magna. Ut mi libero, dictum sit amet mollis non, aliquam et augue';

/**
 * Preprocess the pattern and return the "next" table
 * 
 * @param string $pattern
 */
function preprocessMorrisPratt($pattern, &$nextTable)
{
	$i = 0;
	$j = $nextTable[0] = -1;
	$len = strlen($pattern);
	
	while ($i < $len) {
		while ($j > -1 && $pattern[$i] != $pattern[$j]) {
			$j = $nextTable[$j];
		}
		
		$nextTable[++$i] = ++$j;
	}
}

/**
 * Performs a string search with the Morris-Pratt algorithm
 * 
 * @param string $text
 * @param string $pattern
 */
function MorrisPratt($text, $pattern)
{
	// get the text and pattern lengths
	$n = strlen($text);
	$m = strlen($pattern);
	$nextTable = array();
	
	// calculate the next table
	preprocessMorrisPratt($pattern, $nextTable);
	
	$i = $j = 0;
	while ($j < $n) {
		while ($i > -1 && $pattern[$i] != $text[$j]) {
			$i = $nextTable[$i];
		}
		$i++;
		$j++;
		if ($i >= $m) {
			return $j - $i;
		}
	}
	return -1;
}

// 275
echo MorrisPratt($text, $pattern);
</pre>
<h2>Complexity</h2>
<p>This algorithm needs some time and space for preprocessing. Thus the preprocess of the pattern can be done in O(m), where m is the length of the pattern, while the search itself needs O(m+n). The good news is that you can do the preprocess only once and then perform the search as many times as you wish!</p>
<p>The following chart shows the complexity O(n+m) compared with O(nm) for 5 letter patterns.</p>
<figure id="attachment_3026" style="width: 600px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/04/Morris-Pratt-complexity.png"><img src="/wp-content/uploads/2012/04/Morris-Pratt-complexity.png" alt="Morris-Pratt complexity" title="Morris-Pratt complexity" width="600" height="371" class="size-full wp-image-3026" srcset="/wp-content/uploads/2012/04/Morris-Pratt-complexity.png 600w, /wp-content/uploads/2012/04/Morris-Pratt-complexity-300x185.png 300w" sizes="(max-width: 600px) 100vw, 600px" /></a><figcaption class="wp-caption-text">After pre-processing with O(m) the complexity of searching is O(n+m). You can see on the chart how effective is Morris-Pratt string searching compared to brute force string searching!</figcaption></figure>
<h2>Application</h2>
<h3>Why it&#8217;s cool</h3>
<ol>
<li>Its searching complexity is O(m+n) which is faster than brute force and Rabin-Karp</li>
<li>It’s fairly easy to implement</li>
</ol>
<h3>Why it isn’t cool</h3>
<ol>
<li>It needs additional space and time &#8211; O(m) for pre-processing</li>
<li>It can be optimized a bit (Knuth-Morris-Pratt)</li>
</ol>
<h2>Final Words</h2>
<p>Obviously this algorithm is quite useful because it improves in some very elegant manner the brute force matching. In the other hand you must know that there are faster string searching algorithms like the Boyer-Moore algorithm. However the Morris-Pratt algorithm can be quite useful in many cases, so understanding its principles can be very handy.</p>
<div class='yarpp-related-rss'>
<p>Related posts:<ol>
<li><a href="/2012/04/17/computer-algorithms-boyer-moore-string-search-and-matching/" rel="bookmark" title="Computer Algorithms: Boyer-Moore String Searching">Computer Algorithms: Boyer-Moore String Searching </a></li>
<li><a href="/2012/04/02/computer-algorithms-rabin-karp-string-searching/" rel="bookmark" title="Computer Algorithms: Rabin-Karp String Searching">Computer Algorithms: Rabin-Karp String Searching </a></li>
<li><a href="/2012/03/27/computer-algorithms-brute-force-string-matching/" rel="bookmark" title="Computer Algorithms: Brute Force String Matching">Computer Algorithms: Brute Force String Matching </a></li>
<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>
</ol></p>
</div>
]]></content:encoded>
			<wfw:commentRss>/2012/04/09/computer-algorithms-morris-pratt-string-searching/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>JavaScript Performance: for vs. while</title>
		<link>/2012/01/24/javascript-performance-for-vs-while/</link>
		<comments>/2012/01/24/javascript-performance-for-vs-while/#comments</comments>
		<pubDate>Tue, 24 Jan 2012 14:20:05 +0000</pubDate>
		<dc:creator><![CDATA[Stoimen]]></dc:creator>
				<category><![CDATA[javascript]]></category>
		<category><![CDATA[Computer programming]]></category>
		<category><![CDATA[Computing]]></category>
		<category><![CDATA[Control flow]]></category>
		<category><![CDATA[firebug]]></category>
		<category><![CDATA[Increment]]></category>
		<category><![CDATA[JavaScript programming language]]></category>
		<category><![CDATA[Software engineering]]></category>
		<category><![CDATA[software/hardware]]></category>
		<category><![CDATA[Technology/Internet]]></category>
		<category><![CDATA[While loop]]></category>

		<guid isPermaLink="false">/?p=2635</guid>
		<description><![CDATA[JavaScript Loops If you have read some preformance tests on JavaScript loops, you may have heard that &#8220;while&#8221; is faster than &#8220;for&#8221;. However the question is how faster is &#8220;while&#8221;? Here are some results, but first let&#8217;s take a look on the JavaScript code. The for experiment console.time('for'); for (var i = 0; i < &#8230; <a href="/2012/01/24/javascript-performance-for-vs-while/" class="more-link">Continue reading <span class="screen-reader-text">JavaScript Performance: for vs. while</span> <span class="meta-nav">&#8594;</span></a><div class='yarpp-related-rss'>

Related posts:<ol>
<li><a href="/2010/02/02/firebugs-console-time-accuracy/" rel="bookmark" title="Firebug&#8217;s console.time() accuracy">Firebug&#8217;s console.time() accuracy </a></li>
<li><a href="/2010/02/02/profiling-javascript-with-firebug-console-profile-console-time/" rel="bookmark" title="Profiling JavaScript with Firebug. console.profile() &#038; console.time()!">Profiling JavaScript with Firebug. console.profile() &#038; console.time()! </a></li>
<li><a href="/2010/08/11/quick-look-at-javascript-objects/" rel="bookmark" title="Quick Look at JavaScript Objects">Quick Look at JavaScript Objects </a></li>
<li><a href="/2010/06/02/detecting-pressed-key-with-e-which-in-javascript/" rel="bookmark" title="Detecting Pressed Key with e.which in JavaScript">Detecting Pressed Key with e.which in JavaScript </a></li>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<h2>JavaScript Loops</h2>
<p>If you have read some preformance tests on JavaScript loops, you may have heard that &#8220;while&#8221; is faster than &#8220;for&#8221;. However the question is how faster is &#8220;while&#8221;? Here are some results, but first let&#8217;s take a look on the JavaScript code. </p>
<h4>The <strong>for</strong> experiment</h4>
<pre lang="javascript">
console.time('for');
for (var i = 0; i < 10000000; i++) {
	i / 2;
}
console.timeEnd('for');
</pre>
<h4>The <strong>while</strong> experiment</h4>
<pre lang="javascript">
console.time('while');
var i = 0;
while (i++ < 10000000) {
	i / 2;
}
console.timeEnd('while');
</pre>
<p>Note - these tests are performed and measured with Firebug on Firefox.</p>
<h2>Results</h2>
<p>It's a fact, that you'll get different results as many times as you run this snippet. It depends also on the enviroment and software/hardware specs. That is why I performed them 10 times and then I took the average value. Here are the values of my performance tests. Note that both <strong>for</strong> and <strong>while</strong> perform 10,000,000 iterations.</p>
<p><iframe width='576' height='263' frameborder='0' src='https://docs.google.com/spreadsheet/pub?hl=en_US&#038;hl=en_US&#038;key=0Avxdu4aY4-UGdDktZEJHYUh5RWFLd1prOG52dDdTdUE&#038;single=true&#038;gid=0&#038;output=html&#038;widget=true'></iframe></p>
<h2>And the Winner Is</h2>
<p><strong>While</strong> is the winner with an average result of 83.5 milliseconds, while "for" result is 88 average milliseconds.</p>
<p>As the diagram bellow shows, <strong>the while loop is slightly faster</strong>. However we should be aware that these performance gains are significant for large number of iterations!</p>
<figure id="attachment_2668" style="width: 600px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/01/chart_1-1.png"><img src="/wp-content/uploads/2012/01/chart_1-1.png" alt="JavaScript Performance: for vs. while" title="JavaScript Performance: for vs. while" width="600" height="371" class="size-full wp-image-2668" srcset="/wp-content/uploads/2012/01/chart_1-1.png 600w, /wp-content/uploads/2012/01/chart_1-1-300x185.png 300w" sizes="(max-width: 600px) 100vw, 600px" /></a><figcaption class="wp-caption-text">JavaScript Performance: for vs. while</figcaption></figure>
<div class='yarpp-related-rss'>
<p>Related posts:<ol>
<li><a href="/2010/02/02/firebugs-console-time-accuracy/" rel="bookmark" title="Firebug&#8217;s console.time() accuracy">Firebug&#8217;s console.time() accuracy </a></li>
<li><a href="/2010/02/02/profiling-javascript-with-firebug-console-profile-console-time/" rel="bookmark" title="Profiling JavaScript with Firebug. console.profile() &#038; console.time()!">Profiling JavaScript with Firebug. console.profile() &#038; console.time()! </a></li>
<li><a href="/2010/08/11/quick-look-at-javascript-objects/" rel="bookmark" title="Quick Look at JavaScript Objects">Quick Look at JavaScript Objects </a></li>
<li><a href="/2010/06/02/detecting-pressed-key-with-e-which-in-javascript/" rel="bookmark" title="Detecting Pressed Key with e.which in JavaScript">Detecting Pressed Key with e.which in JavaScript </a></li>
</ol></p>
</div>
]]></content:encoded>
			<wfw:commentRss>/2012/01/24/javascript-performance-for-vs-while/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Object Cloning and Passing by Reference in PHP</title>
		<link>/2011/10/27/object-cloning-and-passing-by-reference-in-php/</link>
		<comments>/2011/10/27/object-cloning-and-passing-by-reference-in-php/#comments</comments>
		<pubDate>Thu, 27 Oct 2011 14:25:17 +0000</pubDate>
		<dc:creator><![CDATA[Stoimen]]></dc:creator>
				<category><![CDATA[micro tutorial]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[C]]></category>
		<category><![CDATA[Clone]]></category>
		<category><![CDATA[Cloning]]></category>
		<category><![CDATA[Comparison of programming languages]]></category>
		<category><![CDATA[Computer programming]]></category>
		<category><![CDATA[Computing]]></category>
		<category><![CDATA[Curly bracket programming languages]]></category>
		<category><![CDATA[Java programming language]]></category>
		<category><![CDATA[PHP programming language]]></category>
		<category><![CDATA[Procedural programming languages]]></category>
		<category><![CDATA[Scripting languages]]></category>
		<category><![CDATA[Software engineering]]></category>

		<guid isPermaLink="false">/?p=2408</guid>
		<description><![CDATA[In PHP everything&#8217;s a reference! I&#8217;ve heard it so many times in my practice. No, these words are too strong! Let&#8217;s see some examples. Passing Parameters by Reference Clearly when we pass parameters to a function it&#8217;s not by reference. How to check this? Well, like this. function f($param) { $param++; } $a = 5; &#8230; <a href="/2011/10/27/object-cloning-and-passing-by-reference-in-php/" class="more-link">Continue reading <span class="screen-reader-text">Object Cloning and Passing by Reference in PHP</span> <span class="meta-nav">&#8594;</span></a><div class='yarpp-related-rss'>

Related posts:<ol>
<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>
<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="/2011/10/20/some-notes-on-the-object-oriented-model-of-php/" rel="bookmark" title="Some Notes on the Object-oriented Model of PHP">Some Notes on the Object-oriented Model of PHP </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>In <a href="/category/php/" title="PHP at stoimen.com">PHP </a>everything&#8217;s a reference! I&#8217;ve heard it so many times in my practice. No, these words are too strong! Let&#8217;s see some examples.<br />
<figure id="attachment_2432" style="width: 480px" class="wp-caption alignnone"><a href="/wp-content/uploads/2011/10/ampersand.jpg"><img src="/wp-content/uploads/2011/10/ampersand.jpg" alt="Passing by reference in PHP can be tricky!" title="ampersand" width="480" height="480" class="size-full wp-image-2432" srcset="/wp-content/uploads/2011/10/ampersand.jpg 480w, /wp-content/uploads/2011/10/ampersand-150x150.jpg 150w, /wp-content/uploads/2011/10/ampersand-300x300.jpg 300w" sizes="(max-width: 480px) 100vw, 480px" /></a><figcaption class="wp-caption-text">Some developers think that everything&#039;s passed by reference in PHP.</figcaption></figure></p>
<h2>Passing Parameters by Reference</h2>
<p>Clearly when we pass parameters to a function it&#8217;s not by reference. How to check this? Well, like this.</p>
<pre lang="PHP">
function f($param)
{
	$param++;
}

$a = 5;
f($a);

echo $a;
</pre>
<p>Now the value of $a equals 5. If it were passed by reference, it would be 6. With a little change of the code we can get it.</p>
<pre lang="PHP">
function f(&$param)
{
	$param++;
}

$a = 5;
f($a);

echo $a;
</pre>
<p>Now the variable&#8217;s value is 6. </p>
<p>So far, so good. Now what about copying objects?<br />
<span id="more-2408"></span></p>
<h2>Objects: A Copy or a Cloning?</h2>
<p>We can check whether by assigning an object to a variable a reference or a copy of the object is passed.</p>
<pre lang="PHP">
class C
{
	public $myvar = 10;
}

$a = new C();
$b = $a;

$b->myvar = 20;

// 20, not 10
echo $a->myvar;
</pre>
<p>The last line outputs 20! This makes it clear. By assigning an object to a variable PHP pass its reference. To make a copy there&#8217;s another approach. We need to change $b = $a, to $b = clone $a;</p>
<pre lang="PHP" escaped="true">
class C
{
	public $myvar = 10;
}

$a = new C();
$b = clone $a;

$b->myvar = 20;

// 10
echo $a->myvar;
</pre>
<h2>Arrays by Reference</h2>
<p>What about arrays? What if I assign an array to a variable?</p>
<pre lang="PHP">
$a = array(20);

$b = $a;
$b[0] = 30;

var_dump($a);
</pre>
<p>What do you think is the value of $a[0]? Well, the answer is: 20! So $b is a copy of the array &#8220;a&#8221;. Instead you should assign explicitly its reference to make &#8220;b&#8221; point to &#8220;a&#8221;.</p>
<pre lang="PHP">
$a = array(20);

$b = &$a;
$b[0] = 30;

var_dump($a);
</pre>
<p>Now $a[0] equals 30!</p>
<p>I think this could be useful!</p>
<div class='yarpp-related-rss'>
<p>Related posts:<ol>
<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>
<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="/2011/10/20/some-notes-on-the-object-oriented-model-of-php/" rel="bookmark" title="Some Notes on the Object-oriented Model of PHP">Some Notes on the Object-oriented Model of PHP </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/27/object-cloning-and-passing-by-reference-in-php/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Does JavaScript undefined Equals undefined?</title>
		<link>/2011/10/21/does-javascript-undefined-equals-undefined/</link>
		<comments>/2011/10/21/does-javascript-undefined-equals-undefined/#comments</comments>
		<pubDate>Fri, 21 Oct 2011 11:36:01 +0000</pubDate>
		<dc:creator><![CDATA[Stoimen]]></dc:creator>
				<category><![CDATA[javascript]]></category>
		<category><![CDATA[Computer programming]]></category>
		<category><![CDATA[Computing]]></category>
		<category><![CDATA[Curly bracket programming languages]]></category>
		<category><![CDATA[ecmascript]]></category>
		<category><![CDATA[JavaScript programming language]]></category>
		<category><![CDATA[js]]></category>
		<category><![CDATA[Procedural programming languages]]></category>
		<category><![CDATA[Scripting languages]]></category>
		<category><![CDATA[Software engineering]]></category>
		<category><![CDATA[tips]]></category>
		<category><![CDATA[tricks]]></category>
		<category><![CDATA[typeof]]></category>
		<category><![CDATA[undefined]]></category>

		<guid isPermaLink="false">/?p=2416</guid>
		<description><![CDATA[Weird JS As you know sometimes JavaScript can be weird. Let&#8217;s see the following example and let&#8217;s try to answer the question: does &#8220;undefined&#8221; equals &#8220;undefined&#8221;. What do I mean? First take a look at the following code. var a; var b = undefined; // alerts "false" alert(b == a); Both a and b are &#8230; <a href="/2011/10/21/does-javascript-undefined-equals-undefined/" class="more-link">Continue reading <span class="screen-reader-text">Does JavaScript undefined Equals undefined?</span> <span class="meta-nav">&#8594;</span></a><div class='yarpp-related-rss'>

Related posts:<ol>
<li><a href="/2010/02/12/how-to-detect-a-variable-existence-in-javascript/" rel="bookmark" title="How to detect a variable existence in JavaScript?">How to detect a variable existence in JavaScript? </a></li>
<li><a href="/2011/07/28/oop-javascript-accessing-public-methods-in-private-methods/" rel="bookmark" title="OOP JavaScript: Accessing Public Methods in Private Methods">OOP JavaScript: Accessing Public Methods in Private Methods </a></li>
<li><a href="/2010/05/24/javascript-objects-coding-style/" rel="bookmark" title="JavaScript Objects Coding Style">JavaScript Objects Coding Style </a></li>
<li><a href="/2011/05/30/object-oriented-javascript-inheritance/" rel="bookmark" title="Object Oriented JavaScript: Inheritance">Object Oriented JavaScript: Inheritance </a></li>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<h2>Weird JS</h2>
<figure id="attachment_2419" style="width: 480px" class="wp-caption alignnone"><a href="/wp-content/uploads/2011/10/question.mark_.jpg"><img src="/wp-content/uploads/2011/10/question.mark_.jpg" alt="Does &quot;undefined&quot; equals &quot;undefined&quot;?" title="question.mark" width="480" height="624" class="size-full wp-image-2419" srcset="/wp-content/uploads/2011/10/question.mark_.jpg 480w, /wp-content/uploads/2011/10/question.mark_-230x300.jpg 230w" sizes="(max-width: 480px) 100vw, 480px" /></a><figcaption class="wp-caption-text">Does JavaScript &quot;undefined&quot; equals &quot;undefined&quot;?</figcaption></figure>
<p>As you know sometimes JavaScript can be weird. Let&#8217;s see the following example and let&#8217;s try to answer the question: does &#8220;undefined&#8221; equals &#8220;undefined&#8221;. What do I mean?</p>
<p>First take a look at the following code.</p>
<pre lang="javascript">
var a;
var b = undefined;

// alerts "false"
alert(b == a);
</pre>
<p>Both <strong>a</strong> and <strong>b</strong> are <strong>undefined</strong>, but they are <strong>NOT</strong> equal. Now let&#8217;s see where it can become a problem.</p>
<p>We have an object with one member variable that is not defined.</p>
<pre lang="javascript">
var f1 = function()
{
	this.myvar;
};

var obj1 = new f1();
</pre>
<p>Now you&#8217;d like to know whether the object &#8220;b&#8221; has the property &#8220;myvar&#8221;. There are lots of examples online, but what&#8217;s the right way?<br />
<span id="more-2416"></span></p>
<h2>Wrong</h2>
<p>Appearantly the value of b.myvar should be undefined.</p>
<pre lang="javascript">
alert(obj1.myvar); // undefined
</pre>
<p>But that doesn&#8217;t mean that it is the same value if the object was declared this way:</p>
<pre lang="javascript">
var f2 = function()
{
	this.myvar = undefined;
};

var obj2 = new f2();
</pre>
<p>This is a completely different thing. Why? In the first case if we try to check whether the property myvar belongs to obj1 we can go wrong with:</p>
<pre lang="javascript">
if (obj1.myvar) // false
</pre>
<p>This is false simply because obj1.myvar is undefined</p>
<pre lang="javascript">
if (obj2.myvar) // false
</pre>
<p>Again is false, because obj2.myvar is undefined.</p>
<p>The same thing happen when using the other &#8220;famous&#8221; approach.</p>
<pre lang="javascript">
if (typeof obj1['myvar'] != 'undefined') // false
if (typeof obj2['myvar'] != 'undefined') // false
</pre>
<p>Clearly this is not the right answer, becase even it is undefined <strong>myvar </strong>belongs to <strong>obj2</strong>!</p>
<h2>Right</h2>
<p>Now let&#8217;s try with <a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object/hasOwnProperty" title="hasOwnProperty on MDN" target="_blank">hasOwnProperty</a> supported by almost every modern browser.</p>
<pre lang="javascript">
if (obj1.hasOwnProperty('myvar')); // false
if (obj2.hasOwnProperty('myvar')); // true
</pre>
<p>Here you can see that when the member variable is explicitly defined as &#8220;undefined&#8221; the object &#8220;has the property&#8221; and hasOwnProperty returns true. Yet again, &#8220;undefined&#8221; does not always equal to &#8220;undefined&#8221;.</p>
<div class='yarpp-related-rss'>
<p>Related posts:<ol>
<li><a href="/2010/02/12/how-to-detect-a-variable-existence-in-javascript/" rel="bookmark" title="How to detect a variable existence in JavaScript?">How to detect a variable existence in JavaScript? </a></li>
<li><a href="/2011/07/28/oop-javascript-accessing-public-methods-in-private-methods/" rel="bookmark" title="OOP JavaScript: Accessing Public Methods in Private Methods">OOP JavaScript: Accessing Public Methods in Private Methods </a></li>
<li><a href="/2010/05/24/javascript-objects-coding-style/" rel="bookmark" title="JavaScript Objects Coding Style">JavaScript Objects Coding Style </a></li>
<li><a href="/2011/05/30/object-oriented-javascript-inheritance/" rel="bookmark" title="Object Oriented JavaScript: Inheritance">Object Oriented JavaScript: Inheritance </a></li>
</ol></p>
</div>
]]></content:encoded>
			<wfw:commentRss>/2011/10/21/does-javascript-undefined-equals-undefined/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Some Notes on the Object-oriented Model of PHP</title>
		<link>/2011/10/20/some-notes-on-the-object-oriented-model-of-php/</link>
		<comments>/2011/10/20/some-notes-on-the-object-oriented-model-of-php/#comments</comments>
		<pubDate>Thu, 20 Oct 2011 15:08:15 +0000</pubDate>
		<dc:creator><![CDATA[Stoimen]]></dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[abstract classes]]></category>
		<category><![CDATA[Abstract type]]></category>
		<category><![CDATA[C]]></category>
		<category><![CDATA[Class]]></category>
		<category><![CDATA[Computer programming]]></category>
		<category><![CDATA[Computing]]></category>
		<category><![CDATA[Education]]></category>
		<category><![CDATA[experiment]]></category>
		<category><![CDATA[how-to]]></category>
		<category><![CDATA[iheritance]]></category>
		<category><![CDATA[Interfaces]]></category>
		<category><![CDATA[Java programming language]]></category>
		<category><![CDATA[Method]]></category>
		<category><![CDATA[micro tutorial]]></category>
		<category><![CDATA[Object-oriented programming]]></category>
		<category><![CDATA[php 5]]></category>
		<category><![CDATA[php class definition]]></category>
		<category><![CDATA[php experiment]]></category>
		<category><![CDATA[php tutorial]]></category>
		<category><![CDATA[php5]]></category>
		<category><![CDATA[Polymorphism in object-oriented programming]]></category>
		<category><![CDATA[Software design patterns]]></category>
		<category><![CDATA[Software engineering]]></category>
		<category><![CDATA[tutorial]]></category>
		<category><![CDATA[Virtual function]]></category>

		<guid isPermaLink="false">/?p=2401</guid>
		<description><![CDATA[PHP 5 introduces interfaces and abstract classes. To become a little clearer, let us see their definitions. Interfaces Object interfaces allow you to create code which specifies which methods a class must implement, without having to define how these methods are handled. Interfaces are defined using the interface keyword, in the same way as a &#8230; <a href="/2011/10/20/some-notes-on-the-object-oriented-model-of-php/" class="more-link">Continue reading <span class="screen-reader-text">Some Notes on the Object-oriented Model of PHP</span> <span class="meta-nav">&#8594;</span></a><div class='yarpp-related-rss'>

Related posts:<ol>
<li><a href="/2011/05/30/object-oriented-javascript-inheritance/" rel="bookmark" title="Object Oriented JavaScript: Inheritance">Object Oriented JavaScript: Inheritance </a></li>
<li><a href="/2011/07/28/oop-javascript-accessing-public-methods-in-private-methods/" rel="bookmark" title="OOP JavaScript: Accessing Public Methods in Private Methods">OOP JavaScript: Accessing Public Methods in Private Methods </a></li>
<li><a href="/2011/10/27/object-cloning-and-passing-by-reference-in-php/" rel="bookmark" title="Object Cloning and Passing by Reference in PHP">Object Cloning and Passing by Reference in PHP </a></li>
<li><a href="/2011/11/14/php-dont-call-the-destructor-explicitly/" rel="bookmark" title="PHP: Don&#8217;t Call the Destructor Explicitly">PHP: Don&#8217;t Call the Destructor Explicitly </a></li>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<p>PHP 5 introduces interfaces and abstract classes. To become a little clearer, let us see their definitions.</p>
<h2>Interfaces</h2>
<blockquote><p>Object interfaces allow you to create code which specifies which methods a class must implement, without having to define how these methods are handled.<br />
Interfaces are defined using the interface keyword, in the same way as a standard class, but without any of the methods having their contents defined.<br />
All methods declared in an interface must be public, this is the nature of an interface. </p>
<p>To implement an interface, the implements operator is used. All methods in the interface must be implemented within a class; failure to do so will result in a fatal error. Classes may implement more than one interface if desired by separating each interface with a comma. </p></blockquote>
<h2>Abstract Classes</h2>
<blockquote><p>PHP 5 introduces abstract classes and methods. Classes defined as abstract may not be instantiated, and any class that contains at least one abstract method must also be abstract. Methods defined as abstract simply declare the method&#8217;s signature &#8211; they cannot define the implementation.</p>
<p>When inheriting from an abstract class, all methods marked abstract in the parent&#8217;s class declaration must be defined by the child; additionally, these methods must be defined with the same (or a less restricted) visibility. For example, if the abstract method is defined as protected, the function implementation must be defined as either protected or public, but not private. Furthermore the signatures of the methods must match, i.e. the type hints and the number of required arguments must be the same. This also applies to constructors as of PHP 5.4. Before 5.4 constructor signatures could differ. </p></blockquote>
<h2>Some Cases</h2>
<p>Now let&#8217;s do a quick experiment. According to the definition of interfaces we can define an interface and than an abstract class can implement this interface.<br />
<span id="more-2401"></span></p>
<pre lang="PHP">
interface A
{
	public function a();
}

abstract class B implements A
{
	public function a()
	{
		return 10;
	}
}
</pre>
<p>However the abstract class cannot be instantiated so we need to extend it.</p>
<pre lang="PHP">
interface A
{
	public function a();
}

abstract class B implements A
{
	public function a()
	{
		return 10;
	}
}

class C extends B
{
	...
}
</pre>
<p>In the first place is completely OK to define an abstract class that does not contain any abstract method. TUsually if a class has one or more abstract methods <em>(Methods defined as abstract simply declare the method&#8217;s signature &#8211; they cannot define the implementation, according to the docs)</em>, it must be defined as abstract. But we can also define an abstract class which has no abstract methods.</p>
<pre lang="PHP">
abstract class B
{
	public function a()
	{
		return 5;
	}
}

class C extends B
{
	public function a()
	{
		return 10;
	}
}

$c = new C();
echo $c->a();
</pre>
<p>OK then what would happen if we had an interface that is implemented by an abstract class, which in turn is extended by a given class. First of all if a class implements an interface, even if it is an abstract class, it must implement all methods defined in the interface. So if the predefined method in the abstract class is marked as abstract, it would result into a fatal error.</p>
<pre lang="PHP">
interface A
{
	public function a();
}

abstract class B implements A
{
	abstract public function a();
}

class C extends B
{
	public function a()
	{
		return 5;
	}
}

$c = new C();
echo $c->a();
</pre>
<p>This is perfectly logical, because in fact each method of the interface must be implemented by his children.</p>
<p><em>&#8220;All methods in the interface must be implemented within a class; failure to do so will result in a fatal error.&#8221;<br />
</em><br />
Fine, but we can have abstract classes with no abstract methods, let&#8217;s try this:</p>
<pre lang="PHP">
interface A
{
	public function a();
}

abstract class B implements A
{
	public function a()
	{
		return 10;
	}
}

class C extends B
{
	public function a()
	{
		return 5;
	}
}

$c = new C();
echo $c->a();
</pre>
<p>This code is working and the result is the returned value from C::a(). However class B is abstract so let&#8217;s go even further. Let&#8217;s define an abstract method, different from the method B::a().</p>
<pre lang="PHP">
interface A
{
	public function a();
}

abstract class B implements A
{
	public function a()
	{
		return 10;
	}
	
	abstract public function b();
}

class C extends B
{
	public function a()
	{
		return 5;
	}
	
	public function b()
	{
		return "hello world!";
	}
}

$c = new C();
echo $c->a();
echo $c->b();
</pre>
<p>Now there&#8217;s a fatal error. Why?</p>
<div class='yarpp-related-rss'>
<p>Related posts:<ol>
<li><a href="/2011/05/30/object-oriented-javascript-inheritance/" rel="bookmark" title="Object Oriented JavaScript: Inheritance">Object Oriented JavaScript: Inheritance </a></li>
<li><a href="/2011/07/28/oop-javascript-accessing-public-methods-in-private-methods/" rel="bookmark" title="OOP JavaScript: Accessing Public Methods in Private Methods">OOP JavaScript: Accessing Public Methods in Private Methods </a></li>
<li><a href="/2011/10/27/object-cloning-and-passing-by-reference-in-php/" rel="bookmark" title="Object Cloning and Passing by Reference in PHP">Object Cloning and Passing by Reference in PHP </a></li>
<li><a href="/2011/11/14/php-dont-call-the-destructor-explicitly/" rel="bookmark" title="PHP: Don&#8217;t Call the Destructor Explicitly">PHP: Don&#8217;t Call the Destructor Explicitly </a></li>
</ol></p>
</div>
]]></content:encoded>
			<wfw:commentRss>/2011/10/20/some-notes-on-the-object-oriented-model-of-php/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>Powerful PHP: Less Known String Manipulation</title>
		<link>/2011/08/18/powerful-php-less-known-string-manipulation/</link>
		<comments>/2011/08/18/powerful-php-less-known-string-manipulation/#comments</comments>
		<pubDate>Thu, 18 Aug 2011 14:01:51 +0000</pubDate>
		<dc:creator><![CDATA[Stoimen]]></dc:creator>
				<category><![CDATA[micro tutorial]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[C]]></category>
		<category><![CDATA[Computer programming]]></category>
		<category><![CDATA[Computing]]></category>
		<category><![CDATA[Data types]]></category>
		<category><![CDATA[Hello world program]]></category>
		<category><![CDATA[Mathematics]]></category>
		<category><![CDATA[Software engineering]]></category>
		<category><![CDATA[String]]></category>

		<guid isPermaLink="false">/?p=2343</guid>
		<description><![CDATA[Yet another thing that&#8217;s great in PHP is the power you have when doing some string manipulation/operation. Here&#8217;s something that is really useful, but I think it remains a bit unknown. Let&#8217;s imagine you need to take the first (or whatever) character of a string. Most developers go to the obvious: $str = 'hello world'; &#8230; <a href="/2011/08/18/powerful-php-less-known-string-manipulation/" class="more-link">Continue reading <span class="screen-reader-text">Powerful PHP: Less Known String Manipulation</span> <span class="meta-nav">&#8594;</span></a><div class='yarpp-related-rss'>

Related posts:<ol>
<li><a href="/2010/08/27/php-what-is-more-powerful-than-list/" rel="bookmark" title="PHP: What is More Powerful Than list()">PHP: What is More Powerful Than list() </a></li>
<li><a href="/2011/07/12/a-javascript-trick-you-should-know/" rel="bookmark" title="A JavaScript Trick You Should Know">A JavaScript Trick You Should Know </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/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>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<p>Yet another thing that&#8217;s great in PHP is the power you have when doing some string manipulation/operation. Here&#8217;s something that is really useful, but I think it remains a bit unknown. Let&#8217;s imagine you need to take the first (or whatever) character of a string. Most developers go to the obvious:</p>
<pre lang="PHP">
$str = 'hello world';
echo substr($str, 0, 1); // outputs "h"
</pre>
<p>But here&#8217;s something better and cleaner.</p>
<pre lang="PHP">
echo $str{0}; // outputs "h"
</pre>
<p>This code chunk return the first character of $str, but it can be used with the same success for any other character of the string. In my opinion this is more cleaner and its really syntactically self documented.</p>
<p>This approach can be useful when trying to check whether the first symbol for instance is &#8220;?&#8221; or &#8220;/&#8221;.</p>
<div class='yarpp-related-rss'>
<p>Related posts:<ol>
<li><a href="/2010/08/27/php-what-is-more-powerful-than-list/" rel="bookmark" title="PHP: What is More Powerful Than list()">PHP: What is More Powerful Than list() </a></li>
<li><a href="/2011/07/12/a-javascript-trick-you-should-know/" rel="bookmark" title="A JavaScript Trick You Should Know">A JavaScript Trick You Should Know </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/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>
</ol></p>
</div>
]]></content:encoded>
			<wfw:commentRss>/2011/08/18/powerful-php-less-known-string-manipulation/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>OOP JavaScript: Accessing Public Methods in Private Methods</title>
		<link>/2011/07/28/oop-javascript-accessing-public-methods-in-private-methods/</link>
		<comments>/2011/07/28/oop-javascript-accessing-public-methods-in-private-methods/#comments</comments>
		<pubDate>Thu, 28 Jul 2011 12:05:42 +0000</pubDate>
		<dc:creator><![CDATA[Stoimen]]></dc:creator>
				<category><![CDATA[javascript]]></category>
		<category><![CDATA[micro tutorial]]></category>
		<category><![CDATA[web development]]></category>
		<category><![CDATA[Accessing Private]]></category>
		<category><![CDATA[C]]></category>
		<category><![CDATA[Class]]></category>
		<category><![CDATA[Computer programming]]></category>
		<category><![CDATA[Computing]]></category>
		<category><![CDATA[Curly bracket programming languages]]></category>
		<category><![CDATA[JavaScript programming language]]></category>
		<category><![CDATA[Object-oriented programming]]></category>
		<category><![CDATA[oop]]></category>
		<category><![CDATA[private]]></category>
		<category><![CDATA[public]]></category>
		<category><![CDATA[Scripting languages]]></category>
		<category><![CDATA[Software engineering]]></category>
		<category><![CDATA[Subroutine]]></category>

		<guid isPermaLink="false">/?p=2339</guid>
		<description><![CDATA[As you know in JavaScript when you define a variable with the special word &#8220;var&#8221; the scope of this variable is within the function. So when you simply wite &#8220;var a = 5&#8221; the variable named &#8220;a&#8221; has a global scope and can be accessed in any function in the global scope. var a = &#8230; <a href="/2011/07/28/oop-javascript-accessing-public-methods-in-private-methods/" class="more-link">Continue reading <span class="screen-reader-text">OOP JavaScript: Accessing Public Methods in Private Methods</span> <span class="meta-nav">&#8594;</span></a><div class='yarpp-related-rss'>

Related posts:<ol>
<li><a href="/2011/05/30/object-oriented-javascript-inheritance/" rel="bookmark" title="Object Oriented JavaScript: Inheritance">Object Oriented JavaScript: Inheritance </a></li>
<li><a href="/2011/10/20/some-notes-on-the-object-oriented-model-of-php/" rel="bookmark" title="Some Notes on the Object-oriented Model of PHP">Some Notes on the Object-oriented Model of PHP </a></li>
<li><a href="/2010/08/11/quick-look-at-javascript-objects/" rel="bookmark" title="Quick Look at JavaScript Objects">Quick Look at JavaScript Objects </a></li>
<li><a href="/2010/03/09/what-make-javascript-closures-work/" rel="bookmark" title="What make JavaScript closures work?">What make JavaScript closures work? </a></li>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<p>As you know in JavaScript when you define a variable with the special word &#8220;var&#8221; the scope of this variable is within the function. So when you simply wite &#8220;var a = 5&#8221; the variable named &#8220;a&#8221; has a global scope and can be accessed in any function in the global scope. </p>
<pre lang="javascript">
var a = 5;

function f() { return a; } // returns 5
</pre>
<p>Thus f will return the value of &#8220;a&#8221; which equals to 5. You can also change the value of the global variable in the function body.</p>
<pre lang="javascript">
var a = 5;
function f() { a = 10; return a; }
console.log(a); // equals to 10
</pre>
<p>Now after we call the function f the value of &#8220;a&#8221; will equal to 10. This is because we reference the global variable &#8220;a&#8221; into the function body without using the keyword &#8220;var&#8221;. This means that if you put the &#8220;var&#8221; keyword the variable &#8220;a&#8221; inside the function body is no longer the same variable as the variable defined outside the body. It becames &#8220;local&#8221; and it&#8217;s visible only inside the function.<br />
<span id="more-2339"></span></p>
<h2>Objects &#038; JavaScript</h2>
<p>Actually in JavaScript functions can be also objects. Any variable defined with the &#8220;var&#8221; keyword becomes private, because it&#8217;s only visible inside the function body, while by using the &#8220;this&#8221; keyword we can define global variables visible outside the function body. Let&#8217;s see na example.</p>
<pre lang="javascript">
var f = function() 
{
	var a = 10;
	this.b = 5;
}

var myfunc = new f();
myfunc.a; // is undefined because a is private
myfunc.b; // equals to 5 because b is public
</pre>
<h2>Public and Private Methods in JavaScript</h2>
<p>As you may know in JS you can define functions inside other functions. Actually this is how you can define classes in JavaScript.</p>
<pre lang="javascript">
var myClass = function() 
{
	var f = function() {
		return 10;
	}
}
</pre>
<p>But this in fact defines a local (private) function into myClass and we cannot access it from the outside world. Here&#8217;s a fully functional class with one public and one private method.</p>
<pre lang="javascript">
var myClass = function()
{
	// public method
	this.a = function() {
		return 10;
	}
	
	// private method
	var b = function() {
		return 5;
	}
}

var c = new myClass();
c.a(); // will return 10
c.b(); // is undefined, because is private
</pre>
<h2>Accessing Private Methods from Public Methods</h2>
<p>Easily we can access private methods from public ones.</p>
<pre lang="javascript">
var myClass = function()
{
	// public method
	this.a = function() {
		return b();
	}
	
	// private method
	var b = function() {
		return 5;
	}
}
</pre>
<p>However accessing public mtehods in private ones is more difficult. That&#8217;s because we cannot use &#8220;this&#8221; into the private methods, just because &#8220;this&#8221; refers to the private method<br />
itself and not to the global method, which is &#8220;myClass&#8221; in our case.</p>
<pre lang="javascript">
var myClass = function()
{
	// public method
	this.a = function() {
		return 10;
	}
	
	// private method
	var b = function() {
		return this.a(); // this will result in an error
	}
}
</pre>
<h2>Accessing Public Methods from Private Methods</h2>
<p>To access public methods in private methods you need to define a variable that points to the global &#8220;this&#8221; object.</p>
<pre lang="javascript">
var myClass = function()
{
	var self = this; 
	
	// public method
	this.a = function() {
		return 10;
	}
	
	// private method
	var b = function() {
		return self.a(); // this will return 10
	}
}
</pre>
<p>This variable gives you the bridge between private methods and global &#8220;this&#8221; pointer.</p>
<div class='yarpp-related-rss'>
<p>Related posts:<ol>
<li><a href="/2011/05/30/object-oriented-javascript-inheritance/" rel="bookmark" title="Object Oriented JavaScript: Inheritance">Object Oriented JavaScript: Inheritance </a></li>
<li><a href="/2011/10/20/some-notes-on-the-object-oriented-model-of-php/" rel="bookmark" title="Some Notes on the Object-oriented Model of PHP">Some Notes on the Object-oriented Model of PHP </a></li>
<li><a href="/2010/08/11/quick-look-at-javascript-objects/" rel="bookmark" title="Quick Look at JavaScript Objects">Quick Look at JavaScript Objects </a></li>
<li><a href="/2010/03/09/what-make-javascript-closures-work/" rel="bookmark" title="What make JavaScript closures work?">What make JavaScript closures work? </a></li>
</ol></p>
</div>
]]></content:encoded>
			<wfw:commentRss>/2011/07/28/oop-javascript-accessing-public-methods-in-private-methods/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
	</channel>
</rss>
