<?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>micro tutorial &#8211; stoimen&#039;s web log</title>
	<atom:link href="/category/micro-tutorial/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 and MySQL Natural Sort</title>
		<link>/2012/06/07/php-and-mysql-natural-sort/</link>
		<comments>/2012/06/07/php-and-mysql-natural-sort/#comments</comments>
		<pubDate>Thu, 07 Jun 2012 11:43:05 +0000</pubDate>
		<dc:creator><![CDATA[Stoimen]]></dc:creator>
				<category><![CDATA[micro tutorial]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[alphabetical order]]></category>
		<category><![CDATA[Entertainment/Culture]]></category>
		<category><![CDATA[Mission: Impossible]]></category>
		<category><![CDATA[Mission: Impossible 2]]></category>
		<category><![CDATA[Mission: Impossible 3]]></category>
		<category><![CDATA[MySQL AB]]></category>
		<category><![CDATA[natural sort order]]></category>
		<category><![CDATA[Order by]]></category>
		<category><![CDATA[Pirates of the Carribean]]></category>
		<category><![CDATA[Sorting]]></category>
		<category><![CDATA[Sorting algorithms]]></category>

		<guid isPermaLink="false">/?p=3176</guid>
		<description><![CDATA[Use Case Let&#8217;s say we have an array of data represented by some text followed by a number. Just like the movies from a movie series like &#8220;Mission Impossible&#8221; or &#8220;Pirates of the Carribean&#8221;. We know that they are often followed by the consecutive number of the episode. Mission: Impossible 1 Mission: Impossible 2 Mission: &#8230; <a href="/2012/06/07/php-and-mysql-natural-sort/" class="more-link">Continue reading <span class="screen-reader-text">PHP and MySQL Natural Sort</span> <span class="meta-nav">&#8594;</span></a><div class='yarpp-related-rss'>

Related posts:<ol>
<li><a href="/2012/02/13/computer-algorithms-insertion-sort/" rel="bookmark" title="Computer Algorithms: Insertion Sort">Computer Algorithms: Insertion Sort </a></li>
<li><a href="/2010/07/09/friday-algorithms-javascript-bubble-sort/" rel="bookmark" title="Friday Algorithms: JavaScript Bubble Sort">Friday Algorithms: JavaScript Bubble Sort </a></li>
<li><a href="/2012/02/20/computer-algorithms-bubble-sort/" rel="bookmark" title="Computer Algorithms: Bubble Sort">Computer Algorithms: Bubble Sort </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[<h2>Use Case</h2>
<p>Let&#8217;s say we have an array of data represented by some text followed by a number. Just like the movies from a movie series like &#8220;Mission Impossible&#8221; or &#8220;Pirates of the Carribean&#8221;. We know that they are often followed by the consecutive number of the episode. </p>
<pre lang="PHP">
Mission: Impossible 1
Mission: Impossible 2
Mission: Impossible 3
...
</pre>
<p>Since we have no more than three or four episodes we can easily sort the array if it&#8217;s not sorted initially.</p>
<pre lang="PHP">
$a = array('Mission: Impossible 2', 'Mission: Impossible 3', 'Mission: Impossible 1');

sort($a);

// Mission: Impossible 1
// Mission: Impossible 2
// Mission: Impossible 3
print_r($a);
</pre>
<p>However in some cases we can have more than 10 episodes. Then we can meet a problem while sorting the array above.</p>
<pre lang="PHP">
$a = array('Episode 1', 'Episode 2', 'Episode 11', 'Episode 112');

sort($a);

// Episode 1
// Episode 11
// Episode 112
// Episode 2
print_r($a);
</pre>
<p>Now because this is by default an alphabetical sort order we get an array that isn&#8217;t sorted to our human undestanding.</p>
<figure id="attachment_3189" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2012/06/Natural-Sort.png"><img src="/wp-content/uploads/2012/06/Natural-Sort.png" alt="Natural Sort" title="Natural Sort" width="620" height="399" class="size-full wp-image-3189" srcset="/wp-content/uploads/2012/06/Natural-Sort.png 620w, /wp-content/uploads/2012/06/Natural-Sort-300x193.png 300w" sizes="(max-width: 620px) 100vw, 620px" /></a><figcaption class="wp-caption-text">Alphabetical vs. Natural sort order</figcaption></figure>
<p>The question is how to overcome this problem?<br />
<span id="more-3176"></span></p>
<h2>PHP</h2>
<p>First the thing we actually need is called &#8220;natural sort&#8221;, so PHP (with its full of handful functions library) takes care for us with <a href="http://www.php.net/manual/en/function.natsort.php" title="PHP: natsort" target="_blank">natsort</a>.</p>
<pre lang="PHP">
$a = array('Episode 1', 'Episode 2', 'Episode 11', 'Episode 112');

natsort($a);

// Episode 1
// Episode 2
// Episode 11
// Episode 112
print_r($a);
</pre>
<p>Now the array is sorted accordingly.</p>
<h2>MySQL</h2>
<p>MySQL in the other hand appears to be more hostile to natural sorting. We can just have ORDER BY with some keyword in order to sort a column using natural sort. </p>
<p>Given the table data:</p>
<pre lang="PHP">
my_table
-----------------------------------------
|	id	|	name		|
-----------------------------------------
|	1	|	Episode 2	|
|	2	|	Episode 1	|
|	3	|	Episode 112	|
|	4	|	Episode 11	|
-----------------------------------------
</pre>
<pre lang="SQL">
SELECT * FROM my_table ORDER BY name;
</pre>
<p>The query above will return the table in an alphabetical order.</p>
<pre lang="PHP">
my_table
-----------------------------------------
|	id	|	name		|
-----------------------------------------
|	2	|	Episode 1	|
|	4	|	Episode 11	|
|	3	|	Episode 112	|
|	1	|	Episode 2	|
-----------------------------------------
</pre>
<p>However there are some &#8220;hacks&#8221;. Here&#8217;s one of them.</p>
<pre lang="SQL">
SELECT * FROM my_table ORDER BY LENGTH(name), name;
</pre>
<p>Now the column is sorted correctly.</p>
<pre lang="PHP">
my_table
-----------------------------------------
|	id	|	name		|
-----------------------------------------
|	2	|	Episode 1	|
|	1	|	Episode 2	|
|	4	|	Episode 11	|
|	3	|	Episode 112	|
-----------------------------------------
</pre>
<div class='yarpp-related-rss'>
<p>Related posts:<ol>
<li><a href="/2012/02/13/computer-algorithms-insertion-sort/" rel="bookmark" title="Computer Algorithms: Insertion Sort">Computer Algorithms: Insertion Sort </a></li>
<li><a href="/2010/07/09/friday-algorithms-javascript-bubble-sort/" rel="bookmark" title="Friday Algorithms: JavaScript Bubble Sort">Friday Algorithms: JavaScript Bubble Sort </a></li>
<li><a href="/2012/02/20/computer-algorithms-bubble-sort/" rel="bookmark" title="Computer Algorithms: Bubble Sort">Computer Algorithms: Bubble Sort </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>/2012/06/07/php-and-mysql-natural-sort/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>jQuery UI Slider IE bugfix</title>
		<link>/2012/02/16/jquery-ui-slider-ie-bugfix/</link>
		<comments>/2012/02/16/jquery-ui-slider-ie-bugfix/#respond</comments>
		<pubDate>Thu, 16 Feb 2012 10:30:26 +0000</pubDate>
		<dc:creator><![CDATA[Stoimen]]></dc:creator>
				<category><![CDATA[javascript]]></category>
		<category><![CDATA[micro tutorial]]></category>
		<category><![CDATA[Computing]]></category>
		<category><![CDATA[jquery]]></category>
		<category><![CDATA[Null]]></category>
		<category><![CDATA[Slider]]></category>
		<category><![CDATA[Widgets]]></category>

		<guid isPermaLink="false">/?p=2718</guid>
		<description><![CDATA[Do your jQuery slider brakes under IE too? When you want to null the sliders on an page, using jQuery UI Slider, somehow the following code works in any browser except IE. // wrong $('.my-slider').slider('value', 0); I say somehow, because according to the documentation this code is simply wrong. It can be used to get &#8230; <a href="/2012/02/16/jquery-ui-slider-ie-bugfix/" class="more-link">Continue reading <span class="screen-reader-text">jQuery UI Slider IE bugfix</span> <span class="meta-nav">&#8594;</span></a><div class='yarpp-related-rss'>

Related posts:<ol>
<li><a href="/2010/06/22/jquery-get-the-selected-option-text/" rel="bookmark" title="jQuery: Get the Selected Option Text">jQuery: Get the Selected Option Text </a></li>
<li><a href="/2010/02/01/writing-a-jquery-plugin-part-2-sample-plugin/" rel="bookmark" title="Writing a jQuery plugin &#8211; (part 2). Sample plugin.">Writing a jQuery plugin &#8211; (part 2). Sample plugin. </a></li>
<li><a href="/2011/04/05/jquery-unbind/" rel="bookmark" title="jQuery.unbind()">jQuery.unbind() </a></li>
<li><a href="/2009/10/21/event-driven-programming-with-jquery-part-2-events-in-jquery/" rel="bookmark" title="Event driven programming with jQuery &#8211; (part 2). Events in jQuery.">Event driven programming with jQuery &#8211; (part 2). Events in jQuery. </a></li>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<h2>Do your jQuery slider brakes under IE too?</h2>
<p>When you want to null the sliders on an page, using jQuery UI Slider, somehow the following code works in any browser except IE.</p>
<pre lang="javascript">
// wrong
$('.my-slider').slider('value', 0);
</pre>
<p>I say somehow, because according to the documentation this code is simply wrong. It can be used to get the value of the slider as it is a getter. You can null the value with the following snippet.</p>
<pre lang="javascript">
// correct
$('.my-slider').slider('option', 'value', 0);
</pre>
<h2>IE Fix</h2>
<p>Another way to null the value is with an anonymous object.</p>
<pre lang="javascript">
// correct
$('.my-slider').slider({ value: 0 });
</pre>
<p>This works on every browser including IE.</p>
<div class='yarpp-related-rss'>
<p>Related posts:<ol>
<li><a href="/2010/06/22/jquery-get-the-selected-option-text/" rel="bookmark" title="jQuery: Get the Selected Option Text">jQuery: Get the Selected Option Text </a></li>
<li><a href="/2010/02/01/writing-a-jquery-plugin-part-2-sample-plugin/" rel="bookmark" title="Writing a jQuery plugin &#8211; (part 2). Sample plugin.">Writing a jQuery plugin &#8211; (part 2). Sample plugin. </a></li>
<li><a href="/2011/04/05/jquery-unbind/" rel="bookmark" title="jQuery.unbind()">jQuery.unbind() </a></li>
<li><a href="/2009/10/21/event-driven-programming-with-jquery-part-2-events-in-jquery/" rel="bookmark" title="Event driven programming with jQuery &#8211; (part 2). Events in jQuery.">Event driven programming with jQuery &#8211; (part 2). Events in jQuery. </a></li>
</ol></p>
</div>
]]></content:encoded>
			<wfw:commentRss>/2012/02/16/jquery-ui-slider-ie-bugfix/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>How to Setup Different Error Messages for Each Zend Form Element Validator</title>
		<link>/2011/11/23/how-to-setup-different-error-messages-for-each-zend-form-element-validator/</link>
		<comments>/2011/11/23/how-to-setup-different-error-messages-for-each-zend-form-element-validator/#comments</comments>
		<pubDate>Wed, 23 Nov 2011 08:25:07 +0000</pubDate>
		<dc:creator><![CDATA[Stoimen]]></dc:creator>
				<category><![CDATA[micro tutorial]]></category>
		<category><![CDATA[zend framework]]></category>
		<category><![CDATA[0]]></category>
		<category><![CDATA[Elementary arithmetic]]></category>
		<category><![CDATA[Error message]]></category>
		<category><![CDATA[Mathematics]]></category>
		<category><![CDATA[measurement]]></category>
		<category><![CDATA[Nothing]]></category>
		<category><![CDATA[Numbers]]></category>
		<category><![CDATA[Pi]]></category>

		<guid isPermaLink="false">/?p=2469</guid>
		<description><![CDATA[Anyone who has worked with that has come across this problem. I&#8217;d like to show different error message on each validator attached to a Zend_Form_Element. Let&#8217;s say we validate an text input field. We want it to contain only digits, but also we&#8217;d like to display different messages when the field is empty and when &#8230; <a href="/2011/11/23/how-to-setup-different-error-messages-for-each-zend-form-element-validator/" class="more-link">Continue reading <span class="screen-reader-text">How to Setup Different Error Messages for Each Zend Form Element Validator</span> <span class="meta-nav">&#8594;</span></a><div class='yarpp-related-rss'>

Related posts:<ol>
<li><a href="/2010/07/07/default-error-handling-in-zend-framework/" rel="bookmark" title="Default Error Handling in Zend Framework">Default Error Handling in Zend Framework </a></li>
<li><a href="/2010/06/04/one-form-multiple-db-records/" rel="bookmark" title="One Form &#8211; Multiple DB Records">One Form &#8211; Multiple DB Records </a></li>
<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/07/22/zend_validate_db_recordexists-in-zend-framework-1-10/" rel="bookmark" title="Zend_Validate_Db_RecordExists in Zend Framework 1.10+">Zend_Validate_Db_RecordExists in Zend Framework 1.10+ </a></li>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<p>Anyone who has worked with that has come across this problem. I&#8217;d like to show different error message on each validator attached to a <a href="http://framework.zend.com/manual/1.11/en/zend.form.standardElements.html" title="Zend Framework: Standard Form Elements" target="_blank">Zend_Form_Element</a>. Let&#8217;s say we validate an text input field. We want it to contain only digits, but also we&#8217;d like to display different messages when the field is empty and when the user has entered something that is different from digits. </p>
<p>It can be done by attaching to the form element two validators: <a href="http://framework.zend.com/manual/en/zend.validate.set.html#zend.validate.set.digits" title="Zend Framework: Standard Validation Classes, Zend_Validate_Digits" target="_blank">Zend_Validate_Digits</a> and <a href="http://framework.zend.com/manual/en/zend.validate.set.html#zend.validate.set.notempty" title="Zend Framework: Standard Validation Classes, Zend_Validate_NotEmpty" target="_blank">Zend_Validate_NotEmpty</a>, but first let&#8217;s see how to change the default &#8220;Value is required and can&#8217;t be empty&#8221; error message of a form field.</p>
<pre lang="PHP">
$element = $form->createElement('text', 'phone');
$element->setLabel('Please, enter your phone number:')
	->setRequired(true)
	->addValidator('Digits');
$form->addElement($element);
</pre>
<p>Here we validate the field with Zend_Validate_Digits and we have set it to be required. Thus everything containing characters, i.e. &#8220;my123name&#8221; or &#8220;007bond&#8221;, will be false, while &#8220;1234&#8221; will be true.</p>
<p><figure id="attachment_2485" style="width: 620px" class="wp-caption alignnone"><a href="/category/zend-framework-on-stoimen-com/"><img src="/wp-content/uploads/2011/11/zend-framework-logo.png" alt="Zend Framework" title="zend-framework-logo" width="620" height="169" class="size-full wp-image-2485" /></a><figcaption class="wp-caption-text">To show different error messages you&#039;ve to attach them per validator and not per form element!</figcaption></figure><br />
 <span id="more-2469"></span><br />
First of all this field is set to be required with the line ->setRequired(true), so we cannot submit the form if the input is empty and we&#8217;ll receive the default error message &#8220;Value is required and can&#8217;t be empty&#8221;. The question is how to change this default message, because as you know sometimes you&#8217;d like to say something different to your users or you&#8217;d like to display error messages on a language different from English. Here&#8217;s how.</p>
<pre lang="PHP">
$element = $form->createElement('text', 'phone');
$element->setLabel('Please, enter your phone number:')
	->setRequired(true)
	->addValidator('Digits')
	->addErrorMessage('Please, type your phone here!');
$form->addElement($element);
</pre>
<p>Now the error message is changed from &#8220;Value is required and can&#8217;t be empty&#8221; to &#8220;Please, type your phone here!&#8221;. </p>
<p>The problem is that when you add more than one validator to a form field you can still show one message regardless of the validator that has failed.</p>
<pre lang="PHP">
$element = $form->createElement('text', 'phone');
$element->setLabel('Please, enter your phone number:')
	->setRequired(true)
	->addValidator('NotEmpty', true)
	->addValidator('Digits', true)
	->addErrorMessage('Please, type your phone here!');
$form->addElement($element);
</pre>
<p>In this case whenever the field is empty or it contains something different from digits, the message shown to the user will be &#8220;Please, type your phone here!&#8221;. The question is can we show different error messages on every validator. This should look something like &#8220;The field cannot be empty!&#8221; when the field is empty and &#8220;Please, enter only digits!&#8221; when the user has entered something into the field, but it doesn&#8217;t contain only digits.</p>
<h2>The Solution</h2>
<p>Actually we have to attach error messages <em><strong>per validator</strong></em>, and not on a form element. Here&#8217;s how it can be done.</p>
<pre lang="PHP">
$notEmpty = new Zend_Validate_NotEmpty();
$notEmpty->setMessage('The field cannot be empty!');

$digits = new Zend_Validate_Digits();
$digits->setMessage('Please, enter only digits');

$element = $form->createElement('text', 'phone');
$element->setLabel('Please, enter your phone:')
	->setRequired(true)
	->addValidator($notEmpty, true)
	->addValidator($digits, true);
$form->addElement($element);
</pre>
<p>Note that we set to &#8220;true&#8221; the second parameter of addValidator. This is important because this way we break the validator&#8217;s chain and when the validation fails on NotEmpty the framework stops the validation of that field against the other validators.</p>
<div class='yarpp-related-rss'>
<p>Related posts:<ol>
<li><a href="/2010/07/07/default-error-handling-in-zend-framework/" rel="bookmark" title="Default Error Handling in Zend Framework">Default Error Handling in Zend Framework </a></li>
<li><a href="/2010/06/04/one-form-multiple-db-records/" rel="bookmark" title="One Form &#8211; Multiple DB Records">One Form &#8211; Multiple DB Records </a></li>
<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/07/22/zend_validate_db_recordexists-in-zend-framework-1-10/" rel="bookmark" title="Zend_Validate_Db_RecordExists in Zend Framework 1.10+">Zend_Validate_Db_RecordExists in Zend Framework 1.10+ </a></li>
</ol></p>
</div>
]]></content:encoded>
			<wfw:commentRss>/2011/11/23/how-to-setup-different-error-messages-for-each-zend-form-element-validator/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>PHP: Don&#8217;t Call the Destructor Explicitly</title>
		<link>/2011/11/14/php-dont-call-the-destructor-explicitly/</link>
		<comments>/2011/11/14/php-dont-call-the-destructor-explicitly/#comments</comments>
		<pubDate>Mon, 14 Nov 2011 16:26:23 +0000</pubDate>
		<dc:creator><![CDATA[Stoimen]]></dc:creator>
				<category><![CDATA[micro tutorial]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[destructor]]></category>
		<category><![CDATA[how-to]]></category>
		<category><![CDATA[Object-oriented programming]]></category>
		<category><![CDATA[oop]]></category>
		<category><![CDATA[php examples]]></category>
		<category><![CDATA[research]]></category>
		<category><![CDATA[Scripting languages]]></category>
		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">/?p=2461</guid>
		<description><![CDATA[&#8220;PHP 5 introduces a destructor concept similar to that of other object-oriented languages, such as C++&#8221;[1] says the documentation for destructors, but let&#8217;s see the following class. class A { public function __construct() { echo 'building an object'; } public function __destruct() { echo 'destroying the object'; } } $obj = new A(); Well, as &#8230; <a href="/2011/11/14/php-dont-call-the-destructor-explicitly/" class="more-link">Continue reading <span class="screen-reader-text">PHP: Don&#8217;t Call the Destructor Explicitly</span> <span class="meta-nav">&#8594;</span></a><div class='yarpp-related-rss'>

Related posts:<ol>
<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="/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="/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/24/javascript-objects-coding-style/" rel="bookmark" title="JavaScript Objects Coding Style">JavaScript Objects Coding Style </a></li>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<p><em>&#8220;PHP 5 introduces a destructor concept similar to that of other object-oriented languages, such as C++&#8221;</em><a href="http://www.php.net/manual/en/language.oop5.decon.php" title="PHP: Constructors and Destructors" target="_blank">[1]</a> says the documentation for destructors, but let&#8217;s see the following class.</p>
<pre lang="PHP">
class A
{
	public function __construct()
	{
		echo 'building an object';
	}
	
	public function __destruct()
	{
		echo 'destroying the object';
	}
}

$obj = new A();
</pre>
<p>Well, as you can not call the constructor explicitly:</p>
<pre lang="PHP">
$obj->__construct();
</pre>
<p>So we should not call the destructor explicitly:</p>
<pre lang="PHP">
$obj->__destruct();
</pre>
<p>The problem is that I&#8217;ve seen this many times, but it&#8217;s a pity that this won&#8217;t destroy the object and it is still a valid PHP code.<br />
<span id="more-2461"></span><br />
<figure id="attachment_2465" style="width: 620px" class="wp-caption alignnone"><a href="/wp-content/uploads/2011/11/destruct.jpg"><img src="/wp-content/uploads/2011/11/destruct.jpg" alt="PHP destructors can&#039;t be called explicitly!" title="destruct" width="620" height="427" class="size-full wp-image-2465" /></a><figcaption class="wp-caption-text">PHP destructors cannot be called explicitely!</figcaption></figure></p>
<p>Constructors and destructors in <a href="/category/php/" title="PHP on stoimen.com">PHP</a> are part of the so called magic methods. Here&#8217;s what the <a href="http://php.net/manual/en/language.oop5.magic.php" title="PHP: Magic Methods" target="_blank">doc page</a> says about them.</p>
<blockquote><p>
The function names __construct(), __destruct(), __call(), __callStatic(), __get(), __set(), __isset(), __unset(), __sleep(), __wakeup(), __toString(), __invoke(), __set_state() and __clone() are magical in PHP classes. You cannot have functions with these names in any of your classes unless you want the magic functionality associated with them.</p></blockquote>
<p>To be more precise let&#8217;s take a look of the definition of destructors. </p>
<blockquote><p>PHP 5 introduces a destructor concept similar to that of other object-oriented languages, such as C++. The destructor method will be called as soon as there are no other references to a particular object, or in any order during the shutdown sequence.</p></blockquote>
<h2>What if I Call the Destructor Explicitly?</h2>
<p>Let&#8217;s see some examples!</p>
<pre lang="PHP">
class A
{
	public function __destruct()
	{
		echo 'destroying the object';
	}
}

$obj = new A();

// prints hello world
echo 'hello world';

// PHP interpreter stops the script execution and prints
// 'destroying the object'
</pre>
<p>This is actually a normal behavior. At the end of the script the interpreter frees the memory. Actually every object has a built-in destructor, just like it has built-in constructor. So even we don&#8217;t define it explicitly, the object has its destructor. Usually this destructor is executed at the end of the script, or whenever the object isn&#8217;t needed anymore. This can happen, for instance, at the end of a function body.</p>
<p>Now if we call the destructor explicitly, which as I said I&#8217;ve seen many times, here&#8217;s what happen.</p>
<pre lang="PHP">
class A
{
	public function __destruct()
	{
		echo 'destroying the object';
	}
}

$obj = new A();

// this is valid and it prints 'destroying the object'
// BUT IT DOES NOT DESTROY THE OBJECT
$obj->__destruct();

// prints hello world
echo 'hello world';

// HERE PHP ACTUALLY DESTROYS THE $obj OBJECT
// ... and again prints 'destroying the object'
</pre>
<p>As you can see calling the destructor explicitly doesn&#8217;t destroy the object. So the question is &#8230;</p>
<h2>How to Destroy an Object Before the Script Stops?</h2>
<p>Well, to destroy an object you can assign a NULL value to it.</p>
<pre lang="PHP">
class A
{
	public function __destruct()
	{
		echo 'destroying the object';
	}
}

$obj = new A();

// prints 'destroying the object'
$obj = null;

// prints 'hello world'
echo 'hello world';

// the script stop its execution
</pre>
<h2>Caution</h2>
<p>Be aware of that if you don&#8217;t clone the object $obj, and simply assign it to another variable, then $obj = null will be pointless. Let&#8217;s see the following example.</p>
<pre lang="PHP">
class A 
{
	public function printMsg()
	{
		echo 'I still exist';
	}
	
	public function __destruct()
	{
		echo 'destroying the object';
	}

}

$obj = new A();

// $newObj is pointing to $obj
$newObj = $obj;

// this doesn't destroy $newObj
// as it appears both $obj and $newObj point to the same memory
// so PHP doesn't free this memory
$obj = null;

// prints 'i still exist'
$newObj->printMsg();

// prints 'hello world'
echo 'hello world';

// now the scripts destroys the "object", which in this
// case is $newObj and prints 'destroying the object'
</pre>
<p>This example shows us that actually by assigning NULL to an object doesn&#8217;t quite destroy it if there are another objects pointing to the same memory.</p>
<pre lang="PHP">
class A 
{
	public function printMsg()
	{
		echo 'I still exist';
	}
	
	public function __destruct()
	{
		echo 'destroying the object';
	}

}

$b = new A();

$d = $c = $b;

$b = null;

$c->printMsg();
$d->printMsg();

// prints 'destroying the object' ONLY ONCE
</pre>
<p>In this last example there are two interesting things to note. First <strong>$b = null</strong> doesn&#8217;t call the destructor, and at the end of the script there&#8217;s only one implicit call of the destructor, although there are two objects.</p>
<h2>Conclusion</h2>
<p>The important thing to note is that you shouldn’t call the destructor of an object explicitly! Not because it will throw an fatal error, but simply because it won’t destroy the object.</p>
<p>[1] <a href="http://www.php.net/manual/en/language.oop5.decon.php" title="PHP: Constructors and Destructors" target="_blank">PHP: Constructors and Destructors</a></p>
<div class='yarpp-related-rss'>
<p>Related posts:<ol>
<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="/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="/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/24/javascript-objects-coding-style/" rel="bookmark" title="JavaScript Objects Coding Style">JavaScript Objects Coding Style </a></li>
</ol></p>
</div>
]]></content:encoded>
			<wfw:commentRss>/2011/11/14/php-dont-call-the-destructor-explicitly/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
		<item>
		<title>How to Check if a Date is More or Less Than a Month Ago with PHP</title>
		<link>/2011/11/04/how-to-check-if-a-date-is-more-or-less-than-a-month-ago-with-php/</link>
		<comments>/2011/11/04/how-to-check-if-a-date-is-more-or-less-than-a-month-ago-with-php/#comments</comments>
		<pubDate>Fri, 04 Nov 2011 14:45:52 +0000</pubDate>
		<dc:creator><![CDATA[Stoimen]]></dc:creator>
				<category><![CDATA[micro tutorial]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[date and time]]></category>
		<category><![CDATA[dates]]></category>
		<category><![CDATA[datetime]]></category>
		<category><![CDATA[how-to]]></category>
		<category><![CDATA[strtotime]]></category>
		<category><![CDATA[tutorial]]></category>
		<category><![CDATA[unix timestamp]]></category>

		<guid isPermaLink="false">/?p=2418</guid>
		<description><![CDATA[Let&#8217;s say we have the following problem: we have to check whether a date is more than a month ago or less than a month ago. Many developers go in the wrong direction by calculating the current month and then subtracting the number of months from it. Of course, this approach is slow and full &#8230; <a href="/2011/11/04/how-to-check-if-a-date-is-more-or-less-than-a-month-ago-with-php/" class="more-link">Continue reading <span class="screen-reader-text">How to Check if a Date is More or Less Than a Month Ago with PHP</span> <span class="meta-nav">&#8594;</span></a><div class='yarpp-related-rss'>

Related posts:<ol>
<li><a href="/2009/08/10/javascript-get-locale-month-with-full-name/" rel="bookmark" title="javascript get locale month with full name">javascript get locale month with full name </a></li>
<li><a href="/2012/03/16/you-think-you-know-php-quiz-results/" rel="bookmark" title="You think you know PHP. Quiz Results!">You think you know PHP. Quiz Results! </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/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>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<p>Let&#8217;s say we have the following problem: we have to check whether a date is more than a month ago or less than a month ago. Many developers go in the wrong direction by calculating the current month and then subtracting the number of months from it. Of course, this approach is slow and full of risks of allowing bugs. Since, two months before January, which is the first month of the year, is actually November, which is the eleventh month. Because of these pitfalls, this approach is entirely wrong.<br />
<figure id="attachment_2442" style="width: 480px" class="wp-caption alignnone"><a href="/wp-content/uploads/2011/11/calendar.jpg"><img src="/wp-content/uploads/2011/11/calendar.jpg" alt="strtotime() is a lot more powerful than you think!" title="calendar" width="480" height="553" class="size-full wp-image-2442" srcset="/wp-content/uploads/2011/11/calendar.jpg 480w, /wp-content/uploads/2011/11/calendar-260x300.jpg 260w" sizes="(max-width: 480px) 100vw, 480px" /></a><figcaption class="wp-caption-text">strtotime() is a lot more powerful than you think!</figcaption></figure></p>
<p>The question is whether PHP cannot help us with built-in functions to perform these calculations for us. It is obvious, that from version 5.3.0 and later, there is an OOP section, which is great, but unfortunately this version is still not updated everywhere. So, how to accomplish the task?</p>
<h2>The Wrong Approach</h2>
<p>As I said, there are many ways to go in the wrong direction. One of them is to subtract 30 days from current date. This is completely wrong, because not every month has 30 days. Here, some developers will begin to predefine arrays to indicate the number of days in each month, which then will be used in their complicated calculations. Here is an example of this wrong approach.</p>
<pre lang="PHP">
echo date('Y-m-d', strtotime(date('Y-m-d')) - 60*60*24*30);
</pre>
<p>This line is full of mistakes. First of all <strong>strtotime(date(&#8216;Y-m-d&#8217;))</strong> can be replaced by the more elegant <strong>strtotime(&#8216;now&#8217;)</strong>, but for this later. Another big mistake is that <strong>60*60*24*30</strong>, which is <strong>number of seconds in 30 days</strong> can be predefined as a constant. Eventually the result is wrong, because not every month has 30 days.</p>
<h2>The Correct Approach</h2>
<p>A small research of the problem and the functions in versions prior of 5.3.0 of PHP is needed. Typical case study of date formatting happen when working with dates from a database. The following code is a classical example.<span id="more-2418"></span></p>
<pre lang="PHP">
// 2008 05 23, 2008-05-23 is stored into the DB
echo date('Y m d', strtotime('2008-05-23'));

// 2008 May 23
echo date('Y F d', strtotime('2008-05-23'));
</pre>
<p>The problem, perhaps, is that too often <a href="http://php.net/manual/en/function.strtotime.php" title="PHP: strtotime" target="_blank">strtotime()</a> is used like this, with exactly this type of strings. However much more interesting is that strtotime() can do much more. </p>
<h2>strtotime() Can Do Much More</h2>
<p>Let us first look at the documentation of this function. What parameters it accepts?</p>
<pre lang="PHP">
int strtotime ( string $time [, int $now = time() ] )
</pre>
<blockquote><p>The function expects to be given a string containing an English date format and will try to parse that format into a Unix timestamp (the number of seconds since January 1 1970 00:00:00 UTC), relative to the timestamp given in now, or the current time if now is not supplied.</p></blockquote>
<p>In particular we are interested in the first parameter, <em>time</em>.</p>
<blockquote><p><em>time </em>&#8211; A date/time string. Valid formats are explained in Date and Time Formats.</p></blockquote>
<p>It is especially important to note what are the <a href="http://www.php.net/manual/en/datetime.formats.php" title="PHP: Supported Date and Time Formats" target="_blank">valid Date and Time Formats</a>.</p>
<p>Here are the supported formats, but most interesting are those that are <a href="http://www.php.net/manual/en/datetime.formats.relative.php" title="PHP: Relative Formats" target="_blank">Relative</a>.</p>
<p>Exactly these formats are very convenient in our case, because they give us the ability to work with human readable strings, and here are some examples from the documentation of strtotime().</p>
<pre lang="PHP">
echo strtotime("now"), "\n";
echo strtotime("10 September 2000"), "\n";
echo strtotime("+1 day"), "\n";
echo strtotime("+1 week"), "\n";
echo strtotime("+1 week 2 days 4 hours 2 seconds"), "\n";
echo strtotime("next Thursday"), "\n";
echo strtotime("last Monday"), "\n";
</pre>
<p>Thus, a valid string would be &#8220;1 month ago&#8221;.</p>
<pre lang="PHP">
// if current date is 2011-11-04, this will return 2011-10-04
echo date('Y-m-d', strtotime('1 month ago'))
</pre>
<p>Or &#8220;-1 month&#8221;:</p>
<pre lang="PHP">
// the same as the example above
echo date('Y-m-d', strtotime('-1 month'));
</pre>
<p>It&#8217;s interesting that &#8220;+1 -1 month&#8221; is also a valid string.</p>
<pre lang="PHP">
// 2011-10-04, if today's 2011-11-04
echo date('Y-m-d', strtotime('+1 -1 month'));
</pre>
<p>In fact strtotime() can do a lot more than most of the developers have ever imagined. Maybe its frequent use with string formatted dates (2010-01-13) makes it a bit unknown. Here are some interesting use cases.</p>
<pre lang="PHP">
// 1970-01-01, Calculations in braces are bad!
echo date('Y-m-d', strtotime('(60*60) minute'));

// 2 months into the future
echo date('Y-m-d', strtotime('-2 months ago'));
</pre>
<p>For instance, do you know how to get the date of the day before yesterday? Yes 2 days before today, but here&#8217;s yet another solution.</p>
<pre lang="PHP">
// 1 day before yesterday
echo date('Y-m-d', strtotime('yesterday -1 day'));
</pre>
<p>Another example is the fully human readable:</p>
<pre lang="PHP">
// get the first monday of the current month
echo date('Y-m-d', strtotime('first monday this month'));
</pre>
<h2>The Solution of the Task</h2>
<p>Finally, what is the solution of the original task? Well, just have to check whether a date is more or less than a month ago.</p>
<pre lang="PHP">
// a random date
$my_date = '2011-09-23';
	
// true if my_date is more than a month ago
(strtotime($my_date) < strtotime('1 month ago'))
</pre>
<div class='yarpp-related-rss'>
<p>Related posts:<ol>
<li><a href="/2009/08/10/javascript-get-locale-month-with-full-name/" rel="bookmark" title="javascript get locale month with full name">javascript get locale month with full name </a></li>
<li><a href="/2012/03/16/you-think-you-know-php-quiz-results/" rel="bookmark" title="You think you know PHP. Quiz Results!">You think you know PHP. Quiz Results! </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/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>
</ol></p>
</div>
]]></content:encoded>
			<wfw:commentRss>/2011/11/04/how-to-check-if-a-date-is-more-or-less-than-a-month-ago-with-php/feed/</wfw:commentRss>
		<slash:comments>4</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>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>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>PHP Strings: How to Get the Extension of a File</title>
		<link>/2011/07/29/php-strings-how-to-get-the-extension-of-a-file/</link>
		<comments>/2011/07/29/php-strings-how-to-get-the-extension-of-a-file/#comments</comments>
		<pubDate>Fri, 29 Jul 2011 06:25:32 +0000</pubDate>
		<dc:creator><![CDATA[Stoimen]]></dc:creator>
				<category><![CDATA[micro tutorial]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[app]]></category>
		<category><![CDATA[Computer file formats]]></category>
		<category><![CDATA[Computing]]></category>
		<category><![CDATA[elegant solution]]></category>
		<category><![CDATA[EXE]]></category>
		<category><![CDATA[Filename]]></category>
		<category><![CDATA[gif]]></category>
		<category><![CDATA[jpeg]]></category>
		<category><![CDATA[path]]></category>

		<guid isPermaLink="false">/?p=2335</guid>
		<description><![CDATA[EXE or GIF or DLL or &#8230; Most of the code chunks I&#8217;ve seen about getting a file extension from a string are based on some sort of string manipulation. $filename = '/my/path/image.jpeg'; echo substr($filename, strrpos($filename, '.') + 1); Howerver there is a more elegant solution. $filename = '/my/path/image.jpeg'; echo strtolower(pathinfo($filename, PATHINFO_EXTENSION)); Thus you rely &#8230; <a href="/2011/07/29/php-strings-how-to-get-the-extension-of-a-file/" class="more-link">Continue reading <span class="screen-reader-text">PHP Strings: How to Get the Extension of a File</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/25/download-files-with-zend-framework/" rel="bookmark" title="Download Files with Zend Framework">Download Files with Zend Framework </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/10/04/some-php-tips-basename/" rel="bookmark" title="Some PHP Tips: basename()">Some PHP Tips: basename() </a></li>
</ol>
</div>
]]></description>
				<content:encoded><![CDATA[<h2>EXE or GIF or DLL or &#8230;</h2>
<p>Most of the code chunks I&#8217;ve seen about getting a file extension from a string are based on some sort of string manipulation.<br />
<figure id="attachment_2351" style="width: 235px" class="wp-caption aligncenter"><a href="/wp-content/uploads/2011/07/filename_extension.jpg"><img class="size-full wp-image-2351" title="filename_extension" src="/wp-content/uploads/2011/07/filename_extension.jpg" alt="Get the Filename Extension with PHP" width="235" height="235" srcset="/wp-content/uploads/2011/07/filename_extension.jpg 235w, /wp-content/uploads/2011/07/filename_extension-150x150.jpg 150w" sizes="(max-width: 235px) 100vw, 235px" /></a><figcaption class="wp-caption-text">If you want to get the filename extension with PHP is better to use pathinfo() than string manipulations</figcaption></figure></p>
<pre lang="php">$filename = '/my/path/image.jpeg';
echo substr($filename, strrpos($filename, '.') + 1);</pre>
<p>Howerver there is a more elegant solution.</p>
<pre lang="php">$filename = '/my/path/image.jpeg';
echo strtolower(pathinfo($filename, PATHINFO_EXTENSION));</pre>
<p>Thus you rely on PHP built in functions and it&#8217;s harder to overlook the exact string manipulation approach.</p>
<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/25/download-files-with-zend-framework/" rel="bookmark" title="Download Files with Zend Framework">Download Files with Zend Framework </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/10/04/some-php-tips-basename/" rel="bookmark" title="Some PHP Tips: basename()">Some PHP Tips: basename() </a></li>
</ol></p>
</div>
]]></content:encoded>
			<wfw:commentRss>/2011/07/29/php-strings-how-to-get-the-extension-of-a-file/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
	</channel>
</rss>
