<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:media="http://search.yahoo.com/mrss/"><channel><title><![CDATA[Codelegance]]></title><description><![CDATA[Where code is beautiful]]></description><link>http://codelegance.com/</link><image><url>http://codelegance.com/favicon.png</url><title>Codelegance</title><link>http://codelegance.com/</link></image><generator>Ghost 1.26</generator><lastBuildDate>Thu, 16 Apr 2026 19:17:34 GMT</lastBuildDate><atom:link href="http://codelegance.com/rss/" rel="self" type="application/rss+xml"/><ttl>60</ttl><item><title><![CDATA[When to use traits in PHP]]></title><description><![CDATA[<div class="kg-card-markdown"><img src="http://codelegance.com/content/images/2016/01/mixing.jpg" style="float: right; margin: 0 0 1em 1em;">
<p>Traits were introduced in PHP 5.4 on March 1st, 2012. Traits provide support for horizontal code reuse, but what is meant by horizontal reuse? Should we be using traits? This article explores what traits are and when we should use them as well as when we should not.</p>
<h2 id="whatisatrait">What</h2></div>]]></description><link>http://codelegance.com/when-to-use-traits/</link><guid isPermaLink="false">59c69f2d61018f0001235ada</guid><category><![CDATA[php]]></category><category><![CDATA[trait]]></category><dc:creator><![CDATA[Paul Morris]]></dc:creator><pubDate>Thu, 14 Nov 2024 18:19:23 GMT</pubDate><content:encoded><![CDATA[<div class="kg-card-markdown"><img src="http://codelegance.com/content/images/2016/01/mixing.jpg" style="float: right; margin: 0 0 1em 1em;">
<p>Traits were introduced in PHP 5.4 on March 1st, 2012. Traits provide support for horizontal code reuse, but what is meant by horizontal reuse? Should we be using traits? This article explores what traits are and when we should use them as well as when we should not.</p>
<h2 id="whatisatrait">What is a trait?</h2>
<p>Anthony Ferrara said it best when he wrote in a <a href="http://stackoverflow.com/a/11939306/1041515">StackOverflow answer</a> that:</p>
<blockquote>
<p>[Traits are] basically just <strong>automated copy and paste</strong>*.</p>
</blockquote>
<p>Unlike manual copy and paste, traits ensure all copies of the code remain consistent—changes to a trait are reflected in all classes using that trait, which is desirable when each copy represents the same idea. Since everything inside a trait is copied directly into a class, even private members of a trait are accessible to the class composing that trait.</p>
<p>Traits are different from includes because include statements can only contain <em>complete classes</em> whereas traits can only represent <em>class fragments</em>. Even if our trait could conceptually function by itself, it is unable to do so because we cannot create instances of traits – the trait must be composed by a class.</p>
<p>Traits were added to PHP to provide <a href="https://wiki.php.net/rfc/horizontalreuse">horizontal reuse</a>. Horizontal reuse is the corollary of <em>vertical reuse</em>, better known as <em>inheritance</em>. When we create a class hierarchy by extending classes it can be said we are extending vertically. When we compose traits in our classes it can be said we are extending horizontally. Although a class can only extend one other class we can use as many traits as desired.</p>
<p>As Ferrara points out, <a href="http://blog.ircmaxell.com/2011/07/are-traits-new-eval.html#more">traits in PHP are actually <em>mixins</em></a>, which means we can not only declare <em>behaviour</em> but also <em>state</em> in a PHP trait. While the formal definition of a trait permits only method declarations, in PHP we can also define member variables, which means they're actually mixins!</p>
<p>Mixins are found in many modern scripting languages including Ruby, Python, JavaScript and, of course, PHP; however they seldom make an appearance in compiled languages like Java and C variants. Even amongst languages that support them, we can usually express solutions to our problems without using traits at all. So do we even need traits? When should we use a trait?</p>
<p><small>* Note that traits are not strictly the same as copy and paste. A class can compose two traits: one  which specifies an abstract method and another which specifies a concrete implementation of the same method. Normally, if we specify the same method name twice in our class we would get an error stating we cannot redeclare the method, but when this ocurrs with traits PHP will resolve the conflict so long as the method signatures are compatible.</small></p>
<h2 id="whenshouldweusetraits">When should we use traits?</h2>
<p>Whenever we have code duplicated in our application we should find a way to eliminate the duplication and reduce our technical debt. Code duplicated <em>n</em> times must be modified in <em>n</em> places when we need to make a change; therefore we would like to ensure that n = 1 such that any change is only made in one place. By reusing code we eliminate duplication.</p>
<p>Traits are just one option for code reuse; we should also consider inheritance and composition. To help decide which solution to use we can apply the following rule.</p>
<p><strong>Traits should be used when we want to reuse code but inheritance and composition are both unsuitable.</strong></p>
<p>Following this rule we can decide how to implement code reuse. The decision tree for this rule looks like the following.</p>
<p><img src="http://codelegance.com/content/images/2016/01/PHP-code-reuse.svg" alt="PHP code reuse decision tree"></p>
<p>Using this model we can explain, for all cases, why traits are an appropriate or inappropriate solution for code reuse. Let's apply this model to a real example.</p>
<h3 id="reusingentityfields">Reusing entity fields</h3>
<p>Notice that, according to our decision tree, a trait is always the last option we consider. We always consider inheritance and composition first; a trait is a last resort when no other option is available to us - and this is good - because traits are difficult to test in silo so we should use them sparingly.</p>
<h2 id="whynottraits">Why not traits</h2>
<ul>
<li>You don't need a trait! Why not just a static class.</li>
<li>They're hard to test.</li>
<li>They hide functionality from the reader.</li>
</ul>
<h2 id="summary">Summary</h2>
<p>We can summarise usage of traits by applying the following rule: <strong>do not use traits unless absolutely necessary</strong>. Some problems that can only be solved with traits and these are the only problems traits should be used to solve. It is therefore our responsibility to first determine whether a problem can be solved without traits, and if it can, prefer those solutions.</p>
</div>]]></content:encoded></item><item><title><![CDATA[Retroactive Rerere]]></title><description><![CDATA[<div class="kg-card-markdown"><p>Thanks to some sick Git magic, I was able to save a PR. <a href="https://jk.gs/git-rerere.html">rerere</a> replays successful conflict resolutions in other branches. It has to be enabled with a config setting: <code>git config --global rerere.enabled true</code>. However, it has to be enabled at the time the merge process begins. Since</p></div>]]></description><link>http://codelegance.com/rerere/</link><guid isPermaLink="false">59c69f2d61018f0001235ade</guid><category><![CDATA[git]]></category><dc:creator><![CDATA[Paul Morris]]></dc:creator><pubDate>Thu, 14 Nov 2024 18:11:01 GMT</pubDate><content:encoded><![CDATA[<div class="kg-card-markdown"><p>Thanks to some sick Git magic, I was able to save a PR. <a href="https://jk.gs/git-rerere.html">rerere</a> replays successful conflict resolutions in other branches. It has to be enabled with a config setting: <code>git config --global rerere.enabled true</code>. However, it has to be enabled at the time the merge process begins. Since I had already resolved the conflicts it was of no help.</p>
<p>However, thanks to some even sicker Git magic I was able to <strong>replay the merge commit</strong> with rerere enabled so it could learn about the conflict resolutions it had previously missed, using the following steps:</p>
<ol start="2">
<li><code>git log -1</code> – Note the merge commit hash.</li>
<li><code>git reset --hard HEAD^</code> – Undo the merge commit.</li>
<li><code>git merge origin/develop</code> – Begin merging again. rerere reports it is watching the merge.</li>
<li><code>git read-tree --reset -u mergecommit</code> – Reset the state of the tree to the original merge commit.</li>
<li><code>git commit</code> – Complete the merge with the original resolutions applied. rerere learns about the resolutions.</li>
</ol>
<p>At this point we can return to the other branches and merge develop and let rerere apply the same conflict resolutions to them.</p>
</div>]]></content:encoded></item><item><title><![CDATA[Effective code review with two simple rules]]></title><description><![CDATA[<div class="kg-card-markdown"><img src="http://codelegance.com/content/images/2017/02/code-review.png" style="float: right; margin: 0 0 1em 1em;">
<p>Code reviews are quickly becoming an industry standard practice for improving software quality. Open source workflows slowly become business best practices as businesses start to appreciate the costs of technical debt and become more concerned with software quality. Over the past decade, the absence of unit testing in the workplace</p></div>]]></description><link>http://codelegance.com/effective-code-review-with-two-simple-rules/</link><guid isPermaLink="false">59c69f2d61018f0001235ad9</guid><category><![CDATA[code review ]]></category><dc:creator><![CDATA[Paul Morris]]></dc:creator><pubDate>Sun, 26 Feb 2017 17:18:00 GMT</pubDate><content:encoded><![CDATA[<div class="kg-card-markdown"><img src="http://codelegance.com/content/images/2017/02/code-review.png" style="float: right; margin: 0 0 1em 1em;">
<p>Code reviews are quickly becoming an industry standard practice for improving software quality. Open source workflows slowly become business best practices as businesses start to appreciate the costs of technical debt and become more concerned with software quality. Over the past decade, the absence of unit testing in the workplace eventually turned into a required developer skill. The days of submitting our first draft as a finished piece of work are gone: peer code reviews are the next developer core competency for software quality, inherited from social coding features of popular open source coding platforms like GitHub.</p>
<p>GitHub released its formal <a href="https://github.com/blog/2256-a-whole-new-github-universe-announcing-new-tools-forums-and-features">code review workflow</a> just a few months ago, but informally, code reviews have been a foundation of the platform for years thanks to features like <a href="https://help.github.com/articles/about-pull-requests/">pull requests</a> and <a href="https://help.github.com/articles/commenting-on-a-pull-request/">inline comments</a>. Its competitors, such as <a href="https://bitbucket.org/product/features">BitBucket</a> and <a href="https://about.gitlab.com/features/">GitLab</a>, share similar features. Code review tools also exist for self-managed solutions, like JIRA plug-in, <a href="https://www.atlassian.com/software/crucible">Crucible</a>.</p>
<p>Code reviews mean we no longer work by ourselves: coding is a social process. Even if we write code by ourselves, at least one other person will check it before it is committed to a shared repository. This has the potential to create conflicts between developers as two or more persons with strong opinions inevitably collide. This is something we're all susceptible to: sometimes we fail to remain humble or objective in the face of criticism of our work, but it is not just the reviewee's fault when conflicts occur; sometimes the reviewer hasn't done a good enough job writing the review.</p>
<h2 id="writingeffectivecodereviews">Writing effective code reviews</h2>
<p>How do we write good code reviews? A <a href="https://github.com/thoughtbot/guides/tree/master/code-review">detailed guide to code reviews</a> has been published by thoughtbot and even <a href="https://gitlab.com/help/development/code_review.md">adopted by GitLab</a>, and it's a great read, but this article proposes effective code review with just two simple rules.</p>
<ol>
<li><strong>Identify a problem</strong>.</li>
<li><strong>Propose a solution</strong>.</li>
</ol>
<p>For every comment we make as a reviewer we must ensure both rules are followed: it is insufficient to do just one of these things. But all too often, a reviewer will leave a comment that does just one, which is often why conflicts and frustration occur between author and reviewer. Let's look at each rule in more detail to see why both are important, but by themselves are insufficient.</p>
<h3 id="identifyaproblem">Identify a problem</h3>
<p>Identifying a problem is crucial to establishing that a change is necessary. If there is no problem, why should the author feel compelled to make a change? <strong>Offer objective evidence that establishes a problem really exists</strong> and thus incentivise the author to make a change.</p>
<p>Sometimes we identify a problem but don't have a solution to offer. It is not strictly incorrect to leave such a comment on a review, but such comments often offer little value because if we don't have a solution there's nothing to suggest the author does either. If we're lucky, someone else might have a solution, but it is incorrect to require the author to make a change based on a problem without a solution because we wouldn't be able to do a better job ourselves.</p>
<h3 id="proposeasolution">Propose a solution</h3>
<p>Take the time to propose at least one solution to the problem. Nothing motivates the author to revisit their code to make a change like seeing a better solution well presented. If we can propose several alternatives, all better than the original, this empowers the author to choose the one they prefer, further encouraging them to make a change. <strong>Don't be afraid to write code in a review</strong>: someone has to write it, and there's no reason why the original author has to do all the work, because social coding is a collaborative process through which the best results can only be delivered by working together.</p>
<p>However, beware of proposing solutions without establishing the existence of a problem! This is the most common mistake made by inexperienced reviewers whom state, <em>do it this way instead</em>, without establishing <em>why</em>. If we cannot explain why our solution is better than the current implementation the author is not compelled to make a change. Sometimes our instincts are correct, our solution <em>is</em> better, but we must develop the skill to objectively express why our approach is better. <strong>Never assume it is obvious to the reader that we are correct without offering proof</strong>.</p>
<p>Sometimes our solution is not better, it is just different. Sometimes, through trying to prove our solution is better, we realize even before publishing our comment that it isn't better, it's just an alternative. In this case we're just inflicting our personal preferences on others; this is why it's paramount to identify the problem before proposing a solution.</p>
<h2 id="beforesubmittingcodeforreview">Before submitting code for review</h2>
<p>The focus of this article is on writing code reviews, but it would be remiss not to mention the author's responsibility when submitting code for review. When we submit code there is just one simple rule to follow.</p>
<ol>
<li><strong>Never submit the first draft</strong>.</li>
</ol>
<p><strong>The first person to review our work must always be ourselves</strong>. It places an unfair burden on the reviewer and wastes their time to spot mistakes we could have found ourselves. Every problem the reviewer identifies in our work should teach us something new; if it does not, we didn't do a good enough job checking our work before submission.</p>
<h2 id="summary">Summary</h2>
<p>Code reviews are becoming commonplace both with collaborators in online communities and with colleagues in the workplace. By following two simple rules we can ensure we write better code reviews, reducing the chance of conflicts and frustration through miscommunication, and insodoing gain the respect and admiration of our peers for helping them write better code together with us.</p>
<p>And remember: don't be too hard on others, or yourself; we all make mistakes.</p>
</div>]]></content:encoded></item><item><title><![CDATA[Semantic method naming]]></title><description><![CDATA[<div class="kg-card-markdown"><img src="http://codelegance.com/content/images/2014/Jun/name-tag.png" style="float: right; margin: 0 0 1em 1em;">
<p>Correctly naming things is <a href="http://www.itworld.com/article/2833265/cloud-computing/don-t-go-into-programming-if-you-don-t-have-a-good-thesaurus.html">the most difficult programming task</a>, along with other documentation tasks. However, this is only because we often afford these tasks insufficient consideration. As with most things, the more we do it the easier it becomes. In this article we will discover how to choose correct names</p></div>]]></description><link>http://codelegance.com/semantic-method-naming/</link><guid isPermaLink="false">59c69f2d61018f0001235ad6</guid><category><![CDATA[naming]]></category><category><![CDATA[documentation]]></category><dc:creator><![CDATA[Paul Morris]]></dc:creator><pubDate>Mon, 21 Dec 2015 09:54:40 GMT</pubDate><content:encoded><![CDATA[<div class="kg-card-markdown"><img src="http://codelegance.com/content/images/2014/Jun/name-tag.png" style="float: right; margin: 0 0 1em 1em;">
<p>Correctly naming things is <a href="http://www.itworld.com/article/2833265/cloud-computing/don-t-go-into-programming-if-you-don-t-have-a-good-thesaurus.html">the most difficult programming task</a>, along with other documentation tasks. However, this is only because we often afford these tasks insufficient consideration. As with most things, the more we do it the easier it becomes. In this article we will discover how to choose correct names for our methods to help ourselves and others read and understand our code.</p>
<p>Although we will focus on naming, documenting and naming complement each other very well. Once we get into the habit of writing documentation for each method, describing what the method <em>does</em>, this helps us name our method correctly. If the documentation is good, usually it is possible to name a method correctly just by picking words from its documentation. We can even use this technique to verify that the method name and its documentation are correct by making sure they agree with each other – if they say different things one of them is wrong.</p>
<p>Lets establish our first and most important rule: all functions and methods <em>do</em> something so they should <strong>begin with a verb</strong> (a <em>doing</em> word). Now we're going to look at how to choose the best verbs to convey the most meaning for what our methods do.</p>
<h2 id="getless">Get less</h2>
<p>The majority of methods we write will return a value and it's a common fallacy to choose <em>get</em> as the verb for too many of these methods. <em>Get</em> is fine for accessor methods that perform simple operations like dereferencing a pointer but doesn't communicate enough information to the caller about the complexity of less trivial methods.</p>
<p>Consider a method that fetches data from a database. It may connect to a remote computer, search for data from multiple sources, perform aggregation and sorting. We could call this method <code>getData()</code> but its verb does not differentiate it from another method that merely gets a simple value already stored in memory. By calling our method <code>fetchData()</code> we imply more work has to be done to retrieve the data.</p>
<p>As a rule, <strong>use <em>get</em> only for methods with constant time complexity</strong>; for anything more complex select a more descriptive verb. For example, if we write a method that uses arithmetic operations to calculate the return value, prefer the verb <em>calculate</em>.</p>
<p>Try to describe what the code in the following method does.</p>
<pre><code class="language-php">function getItem($match) {
    foreach ($this-&gt;items as $item) {
        if ($item === $match) {
            return $item;
        }
    }
}
</code></pre>
<p>We could say this method appears to be searching a collection of items to find one that matches the specified <em>match</em> parameter. From this description we can directly extract a better verb than <em>get</em>; in this case either <em>search</em> or <em>find</em> does a better job of conveying to the caller the complexity of retrieving an item, so we should rename this method, <em>findItem</em>.</p>
<h2 id="donotdo">Do not <em>do</em></h2>
<p>Since all methods <em>do</em> something, choosing <em>do</em> as our verb does not convey any additional information about what our method is doing. <em>Do</em> is one of several common cop-out verbs that should be avoided, along with <em>handle</em>, <em>perform</em>, <em>return</em>, <em>compute</em> and other synonyms.</p>
<p>Some verbs, such as <em>call</em>, <em>execute</em>, <em>run</em> and <em>prepare</em>, perch on the boundary of suitability. It is not always wrong to use these verbs, but if we find ourselves wanting to use them, first pause to consider whether there is a more specific verb to describe what the method is doing.</p>
<h2 id="booleanreturntypes">Boolean return types</h2>
<p>Methods that return <code>true</code> or <code>false</code> <strong>should begin with <em>is</em>, <em>are</em>, <em>was</em>, <em>were</em> or a modal verb</strong>. Modal verbs include <strong><em>can</em>, <em>could</em>, <em>may</em>, <em>might</em>, <em>must</em>, <em>shall</em>, <em>should</em>, <em>will</em> or <em>would</em></strong>. These methods pose questions such as <code>Button::isEnabled()</code>,  <code>Inputs::areValid()</code> or <code>User::canAccess()</code>.</p>
<p>An alternative convention found in Ruby is to define questions by appending a question mark instead of prefixing a verb. The methods from the previous examples would be named <code>Button#enabled?</code>, <code>Inputs#valid?</code> or <code>User#access?</code> respectively. You may wish to use this convention if your language supports this syntax.</p>
<h2 id="subjectinference">Subject inference</h2>
<p>There is a subtle but important difference between functions and methods. A method is a function that runs in the context of an object, such as those we define in a class. We say that the method is <em>bound</em> to the class or object because when it runs it has access to the data stored in that object.</p>
<p>Sometimes it is sufficient to just use the verb when the subject can be inferred from the bound object. For example, a method that saves a message may be called <em>saveMessage</em>. This method includes a subject (<em>message</em>) which specifies the subject of the operation. However, when the subject is the same as the name of the object our method is bound to, we can eliminate it and simply call our method, <em>save</em>. The subject is inferred from the bound object and reads intuitively: <code>$message-&gt;save()</code> as opposed to <code>$message-&gt;saveMessage()</code>.</p>
<h2 id="donotdescribeparameters">Do not describe parameters</h2>
<p>A method's signature comprises both its name and its parameters. When using a method, we have access to both, so it is just duplication to describe the parameters in the method name. The method signature <code>findUserByUserIdAndToken($userId, $token)</code> can be simplified to <code>findUser($userId, $token)</code>.</p>
<p>In languages that support method overloading, such as C++, C# and Java, we can always follow this rule. However, most popular scripting languages such as JavaScript, PHP, Python and Ruby do not support method overloading, meaning we cannot have two methods with the same name but different parameters. In this case it may be necessary to break this rule in order to differentiate between multiple versions of a method.</p>
<h2 id="summary">Summary</h2>
<p>We learned some semantic rules that can be applied to our functions and methods to help determine the correct names. Most importantly, <em>all method names must begin with a verb</em>. If we describe what our method does, and take care to avoid cop-out words, we should be able to select the most appropriate verb to begin our method names.</p>
<p>Some consider documentation more important than code. If code goes wrong and there's no documentation it's difficult to fix because we may not know what it was supposed to do, or why. When a system is clearly defined in descriptive prose we can make informed decisions about the best way to fix it. Correctly naming methods is the first step towards good documentation but to take it a step further we should consider documenting every class and method too, and in turn, this will help us name our methods.</p>
</div>]]></content:encoded></item><item><title><![CDATA[Embracing coercion in PHP]]></title><description><![CDATA[<div class="kg-card-markdown"><img src="http://codelegance.com/content/images/2014/Jul/juggling.jpg" style="float: right; margin: 0 0 1em 1em;">
<p><strong>Coercion</strong> is implicit typecasting for <a href="http://php.net/manual/en/language.types.intro.php">scalar types</a> (integer, float, boolean and string). In this article we look at how we can use coercion as an elegant alternative to <a href="http://php.net/manual/en/language.types.type-juggling.php#language.types.typecasting">explicit typecasting</a>.</p>
<h2 id="coercingtointeger">Coercing to integer</h2>
<p>We can coerce any expression to integer by suffixng <code>|0</code> – bitwise <em>or</em> operator followed by zero. <a href="http://php.net/manual/en/language.operators.bitwise.php">Bitwise</a></p></div>]]></description><link>http://codelegance.com/embracing-coercion-in-php/</link><guid isPermaLink="false">59c69f2d61018f0001235ad4</guid><category><![CDATA[coercion]]></category><category><![CDATA[php]]></category><dc:creator><![CDATA[Paul Morris]]></dc:creator><pubDate>Sun, 08 Feb 2015 16:38:00 GMT</pubDate><content:encoded><![CDATA[<div class="kg-card-markdown"><img src="http://codelegance.com/content/images/2014/Jul/juggling.jpg" style="float: right; margin: 0 0 1em 1em;">
<p><strong>Coercion</strong> is implicit typecasting for <a href="http://php.net/manual/en/language.types.intro.php">scalar types</a> (integer, float, boolean and string). In this article we look at how we can use coercion as an elegant alternative to <a href="http://php.net/manual/en/language.types.type-juggling.php#language.types.typecasting">explicit typecasting</a>.</p>
<h2 id="coercingtointeger">Coercing to integer</h2>
<p>We can coerce any expression to integer by suffixng <code>|0</code> – bitwise <em>or</em> operator followed by zero. <a href="http://php.net/manual/en/language.operators.bitwise.php">Bitwise operators</a> only work on integers so PHP coerces both operands to integer before performing the operation. Performing bitwise <em>or</em> with a value of zero has no effect on the numeric value so we just benefit from the integer coercion.</p>
<p>Integer coercion is equivalent to <code>(int)floor($x)</code>, <code>intval($x)</code> or typecasting with <code>(int)$x</code> or <code>(integer)$x</code>. In some languages this can also be achieved by prefixing <code>~~</code> – two <em>not</em> operators.</p>
<h3 id="examples">Examples</h3>
<table style="max-width: 300px;">
	<tr>
    	<th>Expression
        </th><th>Evaluation
	</th></tr><tr>
    	<td><code>true|0</code>
        </td><td>1
    </td></tr><tr>
    	<td><code>false|0</code>
        </td><td>0
    </td></tr><tr>
    	<td><code>1.6|0</code>
        </td><td>1
    </td></tr><tr>
        <td><code>'1a'|0</code>
        </td><td>1
    </td></tr><tr>
        <td><code>'a1'|0</code>
        </td><td>0
</td></tr></table>
<h2 id="coercingtofloat">Coercing to float</h2>
<p>We can coerce any expression to float by suffixing <code>+0.</code> or <code>+.0</code>. <a href="http://php.net/manual/en/language.types.float.php">Floating-point numbers</a> can be specified without the exponent or significand (but not both), in which case the unspecified part is presumed to be zero; that is, <code>0.</code> and <code>.0</code> are the same as writing <code>0.0</code>.</p>
<p>Float coercion is equivalent to <code>floatval($x)</code> or <code>doubleval($x)</code> or typecasting with <code>(float)$x</code>, <code>(double)$x</code> or <code>(real)$x</code>.</p>
<h3 id="examples">Examples</h3>
<table style="max-width: 300px;">
	<tr>
    	<th>Expression
        </th><th>Evaluation
    </th></tr><tr>
    </tr><tr>
	   	<td><code>true+0.</code>
        </td><td>1.0
    </td></tr><tr>
	   	<td><code>false+0.</code>
        </td><td>0.0
    </td></tr><tr>
	   	<td><code>'1'+0.</code>
        </td><td>1.0
</td></tr></table>
<h2 id="coercingtonumeric">Coercing to numeric</h2>
<p>We can coerce any expression to <a href="http://php.net/manual/en/language.pseudo-types.php">numeric</a>; that is, an integer <em>or</em> float, by prefixing <code>+</code> or <code>-</code>. Although typically used for addition and subtraction as <a href="http://php.net/manual/en/language.operators.arithmetic.php">arithmetic operators</a>, when applied to only one operand we call them <a href="http://en.wikipedia.org/wiki/Unary_operation">unary</a> plus and minus because they only operate on one operand. Unary plus converts its operand to either int or float depending on which is most appropriate; unary minus does the same but also flips the sign.</p>
<p>Numeric coercion cannot be achieved with any other built-in PHP function or syntax.</p>
<h3 id="examples">Examples</h3>
<table style="max-width: 300px;">
	<tr>
    	<th>Expression
        </th><th>Evaluation
    </th></tr><tr>
    	<td><code>+true</code>
        </td><td>1
    </td></tr><tr>
    	<td><code>-true</code>
        </td><td>-1
    </td></tr><tr>
    	<td><code>-false</code>
        </td><td>0
    </td></tr><tr>
        <td><code>-'-1.6a'</code>
        </td><td>1.6
    </td></tr><tr>
        <td><code>+('1'.'6')</code>
        </td><td>16
    </td></tr><tr>
    	<td><code>+'0x10'</code>
        </td><td>16
    </td></tr><tr>
    	<td><code>+'010'</code>
        </td><td>10
    </td></tr><tr>
    	<td><code>+'0b10'</code>
        </td><td>0
</td></tr></table>
<h2 id="coercingtoboolean">Coercing to boolean</h2>
<p>We can coerce any expression to boolean by prefixing at least one <code>!</code> – logical <em>not</em> operator. <a href="http://www.php.net/manual/en/language.operators.logical.php">Logical operators</a> always return a boolean value. We use the <em>not</em> operator because it offers the most concise syntax as the only unary logical operator. The <em>not</em> operator also inverts the meaning of the expression but prefixing a pair (<code>!!</code>) preserves the meaning.</p>
<p>Boolean coercion is equivalent to <code>boolval($x)</code> or typecasting with <code>(bool)$x</code> or <code>(boolean)$x</code>.</p>
<h3 id="examples">Examples</h3>
<table style="max-width: 300px;">
	<tr>
    	<th>Expression
        </th><th>Evaluation
	</th></tr><tr>
    	<td><code>!!true</code>
        </td><td>true
    </td></tr><tr>
    	<td><code>!0</code>
        </td><td>true
    </td></tr><tr>
    	<td><code>!!1</code>
        </td><td>true
    </td></tr><tr>
        <td><code>!!'a'</code>
        </td><td>true
    </td></tr><tr>
        <td><code>!!'0'</code>
        </td><td>false
</td></tr></table>
<p>For more conversions see the true/false columns of the <a href="http://php.net/manual/en/types.comparisons.php#types.comparisions-loose">loose comparisons truth table</a>.</p>
<h2 id="coercingtostring">Coercing to string</h2>
<p>We can coerce any scalar or objects implementing <a href="http://php.net/manual/en/language.oop5.magic.php#object.tostring"><code>__toString()</code></a> to <a href="http://php.net/manual/en/language.types.string.php">string</a> by enclosing them in double quotes.</p>
<p>String coercion is equivalent to <code>strval($x)</code> or typecasting with <code>(string)$x</code>.</p>
<h3 id="example">Example</h3>
<p><a href="http://php.net/manual/en/class.exception.php">Exception</a> implements <code>__toString()</code> providing a string representation of the exception.</p>
<pre><code class="language-php">$e = new Exception('foo');
&quot;$e&quot;;
</code></pre>
<blockquote>
<p>exception 'Exception' with message 'foo' in -:2<br>
Stack trace:<br>
#0 {main}</p>
</blockquote>
<h2 id="practicalapplications">Practical applications</h2>
<p>Some people have tried to <a href="https://github.com/eloquent/typhax">agument the language</a> to provide <a href="https://leanpub.com/typedphp">strong typing</a> for scalars but by working with the grain of the language and embracing coercion we can ensure variables are the types we expect much more easily.</p>
<h3 id="mutatorexample">Mutator example</h3>
<p>Coercion is useful when writing <a href="https://en.wikipedia.org/wiki/Mutator_method">getters and setters</a>. In the following example we want to ensure only integer values are stored in our class when its <code>setInteger</code> method is called.</p>
<pre><code class="language-php">class Bar {
	private $integer;

	public function setInteger($integer) {
    	$this-&gt;integer = $integer|0;
    }
}
</code></pre>
<h3 id="tostringexample">ToString example.</h3>
<p>We want to implement <code>__toString</code> in our class and it is paramount that our implementation actually returns a string to avoid PHP throwing a fatal error. We could use typecasting but coercion solves the problem elegantly.</p>
<pre><code class="language-php">class Foo {
	public $value;
    
    public function __toString() {
    	return &quot;$this-&gt;value&quot;;
    }
}

$foo = new Foo;
$foo-&gt;value = 123;
&quot;$foo&quot;
</code></pre>
<blockquote>
<p>'123'</p>
</blockquote>
<h2 id="summary">Summary</h2>
<table>
	<tr>
    	<th>Type
        </th><th>Coercion
    </th></tr>
    <tr>
    	<td>Integer
        </td><td><code>$x|0</code>
    </td></tr>
    <tr>
    	<td>Float
        </td><td><code>$x+0.</code> or <code>$x+.0</code>
    </td></tr>
	<tr>
    	<td>Numeric
        </td><td><code>+$x</code> or <code>-$x</code>
    </td></tr>
    <tr>
    	<td>Boolean
        </td><td><code>!!$x</code> or <code>!$x</code>
    </td></tr>
    <tr>
    	<td>String
        </td><td><code>"$x"</code>
    </td></tr>
</table>
<h2 id="conclusion">Conclusion</h2>
<p>We explored coercion as a terse alternative to typecasting that works with PHP's concept of <em>type juggling</em> to modify the type of an expression by manupulating its context. Although these examples apply to PHP the concept of coercion can be applied to many scripting languages to modify the types of expressions.</p>
</div>]]></content:encoded></item><item><title><![CDATA[Ideal regex delimiters in PHP]]></title><description><![CDATA[<div class="kg-card-markdown"><p><img src="http://codelegance.com/content/images/2017/09/regex.gif" alt="Regex"></p>
<p>We want to find regular expression <a href="http://php.net/manual/en/regexp.reference.delimiters.php">delimiters</a> that enable us to avoid inserting additional escape sequences into our patterns. This is ideal when we want to inject foreign patterns where we can't guarantee which characters will be used.</p>
<table style="width: auto; float: right; clear: right; margin: 0 0 1em 1em;">
	<caption>Regex grammar
	<tr>
    	<td>Delimiters
    	</td><td><b class="hi">/</b>foo<b class="hi">/</b>i
    </td></tr><tr>
        <td>Pattern
    	</td><td>/<b class="hi">foo</b>/i
    </td></tr><tr>
        <td>Modifier
    	</td><td>/foo/<b class="hi">i</b>
</td></tr></caption></table>
<p>The</p></div>]]></description><link>http://codelegance.com/ideal-regex-delimiters-in-php/</link><guid isPermaLink="false">59c69f2d61018f0001235ad7</guid><category><![CDATA[regex]]></category><category><![CDATA[php]]></category><dc:creator><![CDATA[Paul Morris]]></dc:creator><pubDate>Sat, 12 Jul 2014 23:31:57 GMT</pubDate><content:encoded><![CDATA[<div class="kg-card-markdown"><p><img src="http://codelegance.com/content/images/2017/09/regex.gif" alt="Regex"></p>
<p>We want to find regular expression <a href="http://php.net/manual/en/regexp.reference.delimiters.php">delimiters</a> that enable us to avoid inserting additional escape sequences into our patterns. This is ideal when we want to inject foreign patterns where we can't guarantee which characters will be used.</p>
<table style="width: auto; float: right; clear: right; margin: 0 0 1em 1em;">
	<caption>Regex grammar
	<tr>
    	<td>Delimiters
    	</td><td><b class="hi">/</b>foo<b class="hi">/</b>i
    </td></tr><tr>
        <td>Pattern
    	</td><td>/<b class="hi">foo</b>/i
    </td></tr><tr>
        <td>Modifier
    	</td><td>/foo/<b class="hi">i</b>
</td></tr></caption></table>
<p>The regex grammar table helps understand the language used in this article. You should also know that <a href="http://php.net/manual/en/regexp.reference.meta.php">metacharacter</a> means any character which has special meaning in regex patterns.</p>
<h2 id="pcreknowsnodelimiters">PCRE knows no delimiters</h2>
<p>PHP provides regular expression support using the <strong>Perl Compatible Regular Expressions</strong> (<a href="http://pcre.org/">PCRE</a>) library written in C. Perl has the most comprehensive regex features supporting powerful constructs such as <a href="http://php.net/manual/en/regexp.reference.assertions.php">assertions</a>, <a href="http://php.net/manual/en/regexp.reference.conditional.php">conditionals</a> and <a href="http://php.net/manual/en/regexp.reference.recursive.php">recursion</a> allowing more problems to be solved more easily than other regex flavours.</p>
<p>However, PCRE does not provide a way to specify regular expression options (<a href="http://php.net/manual/en/reference.pcre.pattern.modifiers.php">modifiers</a>) within the pattern; that is, the pattern and options are passed separately to the compiler as shown by the following method signature.</p>
<pre><code class="language-c">pcre *pcre_compile(const char *pattern, int options, ...);
</code></pre>
<p>It is up to implementations like PHP to decide how to expose modifiers to us. Most implementations map each option to a single letter such as the <code>i</code> modifier which sets the <code>PCRE_CASELESS</code> option enabling case-insensitive matching. Modifiers are typically appended to the pattern and separated by <em>delimiters</em> but PCRE itself has no concept of delimiters.</p>
<h2 id="delimitersinphp">Delimiters in PHP</h2>
<p>Most implementations use a pair of slashes to delimit patterns, for example, <code>/pattern/</code>. In PHP we may elect any symbol (except backslash) to delimit our pattern with the crucial caveat that each occurrence of our delimiter <em>within</em> the pattern must be escaped by prefixing a backslash (<code>\</code>), as shown below.</p>
<ul>
<li><code>/a/b/</code> – invalid</li>
<li><code>/a\/b/</code> – <span class="hi">valid</span></li>
<li><code>#a/b#</code> – <span class="hi">valid</span></li>
</ul>
<p>We'd like to be able to choose a delimiter that will never appear in our pattern to avoid having to insert unnecessary escapes. If we're hard coding our pattern this should be possible even if we have to change the delimiter a few times as our pattern evolves. However, if we need to insert a user-defined pattern how can we ensure that our chosen delimiter will not conflict? The solution lies in <em>asymmetric delimiters</em>.</p>
<h3 id="asymmetricdelimiters">Asymmetric delimiters</h3>
<p>We may never know why PHP is unable to detect the last occurrence of our delimiter without requiring us to escape every occurrence before it but fortunately there is another solution. PHP inherits <a href="http://perldoc.perl.org/perlop.html#Quote-and-Quote-like-Operators">Perl's bracket delimiter syntax</a> giving us four asymmetric delimiters to choose from:</p>
<ul>
<li><code>(pattern)i</code> – round brackets</li>
<li><code>[pattern]i</code> – square brackets</li>
<li><code>{pattern}i</code> – curly brackets</li>
<li><code>&lt;pattern&gt;i</code> – angled brackets</li>
</ul>
<h4 id="angledbrackets">Angled brackets</h4>
<p>Each pair of brackets except for angled brackets are considered metacharacters in patterns but have no special meaning as delimiters. Since angled brackets are not metacharacters we might think we could avoid having to escape them in patterns delimited by angle brackets.</p>
<ul>
<li><code>&lt;&gt;&gt;</code> – invalid</li>
<li><code>&lt;\&gt;&gt;</code> – <span class="hi">valid</span></li>
<li><code>&lt;&lt;&gt;</code> – invalid</li>
<li><code>&lt;\&lt;&gt;</code> – <span class="hi">valid</span></li>
</ul>
<p>Unfortunately, angled brackets have to be escaped when used as delimiters just like symmetric delimiters, except now we've inherited the burden of having to escape two characters instead of just one! Angled brackets are a step backward but the other three bracket types offer something different.</p>
<h4 id="nonangledbrackets">Non-angled brackets</h4>
<p>When we use non-angled brackets as our delimiters we can still use whichever bracket type we choose as normal in patterns without having to escape them and without changing their meaning – exactly what we've been searching for! Each of the following expressions match the character <em>a</em> once.</p>
<ul>
<li><code>((a))</code> – <span class="hi">valid</span></li>
<li><code>[[a]]</code> – <span class="hi">valid</span></li>
<li><code>{a{1}}</code> – <span class="hi">valid</span></li>
</ul>
<h3 id="theidealdelimiter">The ideal delimiter</h3>
<p>We have been searching for a delimiter that does not require us to insert additional escapes into our pattern and any of the non-angled brackets serve this purpose, but we still have to choose one of them, so which is best?</p>
<p>Technically each options is as good as the other but curly brackets are the least common metacharacter of the three, and as a quantifier, cannot appear at the start of an expression so they can only double-up at the end. This sets curly brackets apart as the most suitable delimiters to use in PHP.</p>
<h2 id="conclusion">Conclusion</h2>
<p>Three different asymmetric delimiters allow us to avoid extra escaping: round brackets <code>()</code>, square brackets <code>[]</code> and curly brackets <code>{}</code>. As the least used metacharacter, less likely to be confused with other parts of a pattern, curly brackets may be the ideal delimiters for most expressions.</p>
<style>
.hi { color: #43d1b2; }
</style></div>]]></content:encoded></item><item><title><![CDATA[New PHP 5 syntax reference]]></title><description><![CDATA[<div class="kg-card-markdown"><img src="http://codelegance.com/content/images/2014/Jun/new.png" style="float: right; margin: 0 0 1em 1em;">
<p>We briefly review the major new PHP language syntax introduced in each version since 5.3 – the version that birthed the features that paved the way for the <a href="http://transmission.vehikl.com/why-php-doesnt-suck-anymore/">prevailing</a> <a href="https://donatstudios.com/PHP-Has-Grown-Up">PHP</a> <a href="https://www.oreilly.com/ideas/the-new-php">renaissance</a>.</p>
<table style="max-width: 300px; float: right; margin: 0 0 1em 1em;">
	<tr>
    	<td class="always">Always</td>
        <td>Every project.</td>
    </tr>
	<tr>
    	<td class="common">Common</td>
        <td>Most projects.</td>
    </tr>
	<tr>
    	<td class="uncommon">Uncommon</td>
        <td>Some projects.</td>
    </tr>
	<tr>
    	<td class="rare">Rare</td>
        <td>Almost never.</td>
    </tr>
</table>
<p>Features are ordered by how frequently you</p></div>]]></description><link>http://codelegance.com/new-php-syntax-reference/</link><guid isPermaLink="false">59c69f2d61018f0001235ad5</guid><category><![CDATA[reference]]></category><category><![CDATA[php]]></category><dc:creator><![CDATA[Paul Morris]]></dc:creator><pubDate>Sun, 22 Jun 2014 07:57:43 GMT</pubDate><content:encoded><![CDATA[<div class="kg-card-markdown"><img src="http://codelegance.com/content/images/2014/Jun/new.png" style="float: right; margin: 0 0 1em 1em;">
<p>We briefly review the major new PHP language syntax introduced in each version since 5.3 – the version that birthed the features that paved the way for the <a href="http://transmission.vehikl.com/why-php-doesnt-suck-anymore/">prevailing</a> <a href="https://donatstudios.com/PHP-Has-Grown-Up">PHP</a> <a href="https://www.oreilly.com/ideas/the-new-php">renaissance</a>.</p>
<table style="max-width: 300px; float: right; margin: 0 0 1em 1em;">
	<tr>
    	<td class="always">Always</td>
        <td>Every project.</td>
    </tr>
	<tr>
    	<td class="common">Common</td>
        <td>Most projects.</td>
    </tr>
	<tr>
    	<td class="uncommon">Uncommon</td>
        <td>Some projects.</td>
    </tr>
	<tr>
    	<td class="rare">Rare</td>
        <td>Almost never.</td>
    </tr>
</table>
<p>Features are ordered by how frequently you are likely to use them from a practical programming perspective according to the table.</p>
<p>If a feature does not appear in this reference it is because it is not syntax or is a minor modification of existing syntax.</p>
<h2 id="newinphp53">New in PHP 5.3</h2>
<p>Released <a href="http://php.net/ChangeLog-5.php#5.3.0">June 30th, 2009</a>.</p>
<table>
	<tr>
    	<th width="31%">Feature</th>
        <th>Examples</th>
        <th width="11%">Frequency</th>
    </tr>
	<tr>
    	<td><a href="http://php.net/manual/en/language.namespaces.php">Namespaces</a></td>
        <td>
			<code>namespace Foo;</code>
            <br>
            <code>namespace { $global; }</code>
        </td>
        <td class="always">Always</td>
    </tr>
    <tr>
        <td><a href="http://php.net/manual/en/functions.anonymous.php">Closures</a></td>
        <td>
        	<code>$callable = function($x, $y) use ($local) {};</code>
        </td>
        <td class="common">Common</td>
    </tr>
    <tr>
        <td><a href="http://php.net/manual/en/language.operators.comparison.php#language.operators.comparison.ternary">Ternary shorthand</a></td>
        <td><code>$this ?: $that;</code></td>
        <td class="common">Common</td>
    </tr>
    <tr>
        <td><a href="http://php.net/manual/en/language.oop5.late-static-bindings.php">Late static binding</a></td>
        <td><code>static::overrideMe();</code>
        </td><td class="common">Common</td>
    </tr>
    <tr>
        <td><a href="http://php.net/manual/en/language.types.string.php#language.types.string.syntax.nowdoc">Nowdoc</a></td>
        <td>
        	<code>&lt;&lt;&lt;'SQL'
	SELECT injection, proof FROM $table;
SQL;</code>
        </td>
        <td class="uncommon">Uncommon</td>
    </tr>
    <tr>
        <td><a href="http://php.net/manual/en/control-structures.goto.php">Jump labels</a></td>
        <td><code>goto hell;</code></td>
        <td class="rare">Rare</td>
    </tr>
</table>
<h2 id="newinphp54">New in PHP 5.4</h2>
<p>Released <a href="http://php.net/ChangeLog-5.php#5.4.0">March 1st, 2012</a>.</p>
<table>
	<tr>
    	<th width="31%">Feature</th>
        <th>Examples</th>
        <th width="11%">Frequency</th>
    </tr>
	<tr>
    	<td><a href="http://php.net/manual/en/language.types.array.php#language.types.array.syntax">Short array syntax</a></td>
        <td><code>['foo']</code></td>
        <td class="always">Always</td>
    </tr>
	<tr>
    	<td>Class member access on instantiation</td>
        <td><code>(new Class)->member();</code></td>
        <td class="common">Common</td>
    </tr>
	<tr>
    	<td><a href="http://php.net/manual/en/language.oop5.traits.php">Traits</a></td>
        <td><code>trait Foo extends Bar {}
class Fubar { use Foo; }</code></td>
        <td class="uncommon">Uncommon</td>
    </tr>
	<tr>
    	<td>Function array dereferencing</td>
        <td><code>$foo->toArray()[0];</code></td>
        <td class="uncommon">Uncommon</td>
    </tr>
	<tr>
    	<td><a href="http://php.net/manual/en/language.types.integer.php#language.types.integer.syntax">Binary number format</a></td>
        <td><code>0b10100111001</code></td>
        <td class="rare">Rare</td>
    </tr>
</table>
<h2 id="newinphp55">New in PHP 5.5</h2>
<p>Released <a href="http://php.net/ChangeLog-5.php#5.5.0">June 20th, 2013</a>.</p>
<table>
	<tr>
    	<th width="31%">Feature</th>
        <th>Examples</th>
        <th width="11%">Frequency</th>
    </tr>
	<tr>
    	<td><a href="http://php.net/manual/en/migration55.new-features.php#migration55.new-features.class-name">Class name resolution</a></td>
        <td><code>Foo::class</code></td>
        <td class="common">Common</td>
    </tr>
	<tr>
    	<td><a href="http://php.net/manual/en/language.generators.php">Generators</a></td>
        <td><code>yield $x;</code></td>
        <td class="common">Common</td>
    </tr>
	<tr>
    	<td><a href="http://php.net/manual/en/language.exceptions.php">Finally</a></td>
        <td><code>try { $h = fopen('foo'); }
finally { fclose($h); }</code></td>
        <td class="common">Common</td>
    </tr>
	<tr>
    	<td><a href="http://php.net/manual/en/control-structures.foreach.php#control-structures.foreach.list">Nested array unpacking</a></td>
        <td><code>foreach ([[1], [2]] as list($n)) {}</code></td>
        <td class="rare">Rare</td>
    </tr>
	<tr>
    	<td><a href="http://php.net/manual/en/migration55.new-features.php#migration55.new-features.const-dereferencing">Array and string literal dereferencing</a></td>
        <td><code>[1, 2][$x];
'1234'[$x];</code></td>
        <td class="rare">Rare</td>
    </tr>
</table>
<h2 id="newinphp56">New in PHP 5.6</h2>
<p>Released <a href="http://php.net/ChangeLog-5.php#5.6.0">August 28th, 2014</a>.</p>
<table>
	<tr>
    	<th width="31%">Feature</th>
        <th>Examples</th>
        <th width="11%">Frequency</th>
    </tr>
	<tr>
    	<td><a href="http://php.net/manual/en/migration56.new-features.php#migration56.new-features.const-scalar-exprs">Constant scalar expressions</a></td>
        <td><code>const TWO = 1 + 1;</code></td>
        <td class="common">Common</td>
    </tr>
    <tr>
    	<td><a href="http://php.net/manual/en/migration56.new-features.php#migration56.new-features.splat">Argument unpacking</a> (splat)</td>
        <td><code>parse(...$argv);</code></td>
        <td class="uncommon">Uncommon</td>
    </tr>
	<tr>
    	<td><a href="http://php.net/manual/en/migration56.new-features.php#migration56.new-features.variadics">Variadic functions</a></td>
        <td><code>function(...$params) {}</code></td>
        <td class="uncommon">Uncommon</td>
    </tr>
    <tr>
    	<td><a href="http://php.net/manual/en/migration56.new-features.php#migration56.new-features.exponentiation">Exponentiation operator</a></td>
        <td><code>2 ** 10</code></td>
        <td class="uncommon">Uncommon</td>
    </tr>
    <tr>
    	<td><a href="http://php.net/manual/en/migration56.new-features.php#migration56.new-features.use">Use function and use const</a></td>
        <td><code>use function Name\Space\f;
use const Name\Space\FOO;</code></td>
        <td class="rare">Rare</td>
    </tr>
</table>
<h2 id="references">References</h2>
<ol>
<li><a href="http://php.net/manual/en/migration53.new-features.php">http://php.net/manual/en/migration53.new-features.php</a></li>
<li><a href="http://php.net/manual/en/migration54.new-features.php">http://php.net/manual/en/migration54.new-features.php</a></li>
<li><a href="http://php.net/manual/en/migration55.new-features.php">http://php.net/manual/en/migration55.new-features.php</a></li>
<li><a href="http://php.net/manual/en/migration56.new-features.php">http://php.net/manual/en/migration56.new-features.php</a></li>
</ol>
<style>
th:nth-child(3) { white-space: nowrap; }
.always:nth-child(n) { color: #fff; background: #15d8ae; opacity: .55; text-align: center; vertical-align: middle; }
.common:nth-child(n) { color: #fff; background: #1cc29f; opacity: .55; text-align: center; vertical-align: middle; }
.uncommon:nth-child(n) { color: #fff; background: #1aa387; opacity: .55; text-align: center; vertical-align: middle; }
.rare:nth-child(n) { color: #fff; background: #198872; opacity: .55; text-align: center; vertical-align: middle; }
</style></div>]]></content:encoded></item><item><title><![CDATA[Array merging in PHP]]></title><description><![CDATA[<div class="kg-card-markdown"><p><img src="http://codelegance.com/content/images/2017/09/merge.jpg" alt="merge"></p>
<p>Correctly merging two arrays into a single array requires thinking about the type of data we have. Is our data flat or does it contain nested arrays? What should happen when both arrays contain the same key?</p>
<p>PHP provides three ways to merge arrays.</p>
<ol>
<li>The array union operator: <a href="http://www.php.net/manual/en/language.operators.array.php">+</a>.</li>
<li>The <a href="http://php.net/manual/en/function.array-merge.php">array_</a></li></ol></div>]]></description><link>http://codelegance.com/array-merging-in-php/</link><guid isPermaLink="false">59c69f2d61018f0001235ad3</guid><category><![CDATA[array]]></category><category><![CDATA[php]]></category><dc:creator><![CDATA[Paul Morris]]></dc:creator><pubDate>Sat, 14 Jun 2014 16:00:00 GMT</pubDate><content:encoded><![CDATA[<div class="kg-card-markdown"><p><img src="http://codelegance.com/content/images/2017/09/merge.jpg" alt="merge"></p>
<p>Correctly merging two arrays into a single array requires thinking about the type of data we have. Is our data flat or does it contain nested arrays? What should happen when both arrays contain the same key?</p>
<p>PHP provides three ways to merge arrays.</p>
<ol>
<li>The array union operator: <a href="http://www.php.net/manual/en/language.operators.array.php">+</a>.</li>
<li>The <a href="http://php.net/manual/en/function.array-merge.php">array_merge</a> function.</li>
<li>The <a href="http://php.net/manual/en/function.array-merge-recursive.php">array_merge_recursive</a> function.</li>
</ol>
<p>We may also need <a href="http://www.zendframework.com/apidoc/2.3/classes/Zend.Stdlib.ArrayUtils.html#merge">Zend\Stdlib\ArrayUtils::merge</a> which ships as part of <a href="http://www.zendframework.com/">Zend Framework 2</a> and can be included in our application by requiring <a href="https://packagist.org/packages/zendframework/zend-stdlib"><code>zendframework/zend-stdlib</code></a> with <a href="http://getcomposer.org/">Composer</a>.</p>
<h2 id="choosingtherightfunction">Choosing the right function</h2>
<h3 id="structure">Structure</h3>
<p>When our data is <strong>flat</strong> we can use <code>array_merge</code> or the <code>+</code> operator. When we want to merge nested arrays we must use a <strong>recursive</strong> function like <code>array_merge_recursive</code> or <code>ArrayUtils::merge</code>.</p>
<h3 id="duplicates">Duplicates</h3>
<p>Duplicates occur when both input arrays contain the same key. Only keys are considered when determining duplicates, not values. Duplicates create a merge conflict that is resolved by either <strong>appending</strong> or <strong>replacing</strong> duplicate key values.</p>
<p>Only the <code>+</code> operator behaves consistently (it always replaces duplicates); the other merge functions change behaviour depending on whether the key type is <strong>numeric</strong> or a <strong>string</strong> as shown below. However, <code>ArrayUtils::merge</code> will behave consistently when <code>true</code> is passed as the third parameter <a href="https://github.com/zendframework/zf2/commit/468860b253704aa0c4987b5e766d7efeb120e503#diff-9c0268943ecefa8bb38487a3f1b196aeL245">since Zend Framework 2.2.6</a>.</p>
<h4 id="numerickeys">Numeric keys</h4>
<p>With the exception of the <code>+</code> operator, values in numeric keys are <strong>appended and reindexed</strong>. The <code>+</code> operator always replaces duplicate keys regardless of the type.</p>
<table>
	<thead>
		<tr>
			<td></td>
            <th width="40%">Append</th>
		    <th width="40%">Replace</th>
		</tr>
	</thead>
	<tbody>
        <tr>
        	<th>Flat</th>
            <td>
            	<a href="http://php.net/manual/en/function.array-merge.php">array_merge</a>
            </td>
            <td>
            	<a href="http://www.php.net/manual/en/language.operators.array.php">+</a>
            </td>
        </tr>
	    <tr>
	        <th>Recursive</th>
        	<td>
				<a href="http://php.net/manual/en/function.array-merge-recursive.php">
            	array_merge_recursive</a>
                <br>
                <a href="http://www.zendframework.com/apidoc/2.3/classes/Zend.Stdlib.ArrayUtils.html#merge">
                ArrayUtils::merge</a>
            </td>
            <td>
	            <a href="http://www.zendframework.com/apidoc/2.3/classes/Zend.Stdlib.ArrayUtils.html#merge">
   	            ArrayUtils::merge(<i>x</i>, <i>y</i>, true)</a>
            </td>
        </tr>
    </tbody>
</table>
<h5 id="examples">Examples</h5>
<p>In these examples both arrays have the same implicit numeric key (0). The <code>+</code> operator drops duplicates found in the right operand.</p>
<pre><code class="language-php">[1] + [2];
</code></pre>
<blockquote>
<p>[0 =&gt; 1]</p>
</blockquote>
<p>The merge functions append values and reindex keys. Since the input arrays are flat in these examples, the result is the same for the recursive functions.</p>
<pre><code class="language-php">array_merge([1], [2]);
</code></pre>
<blockquote>
<p>[0 =&gt; 1, 1 =&gt; 2]</p>
</blockquote>
<h4 id="stringkeys">String keys</h4>
<p>With the exception of <code>array_merge_recursive</code>, values in duplicate string keys are <strong>replaced</strong>. However, <code>array_merge_recursive</code> always appends duplicate keys regardless of the type.</p>
<table>
	<thead>
		<tr>
			<td></td>
            <th width="40%">Append</th>
		    <th width="40%">Replace</th>
		</tr>
	</thead>
	<tbody>
        <tr>
        	<th>Flat</th>
            <td></td>
            <td>
              	<a href="http://php.net/manual/en/function.array-merge.php">array_merge</a>
                <br>
            	<a href="http://www.php.net/manual/en/language.operators.array.php">+</a>
            </td>
        </tr>
	    <tr>
	        <th>Recursive</th>
        	<td>
				<a href="http://php.net/manual/en/function.array-merge-recursive.php">
            	array_merge_recursive</a>
            </td>
            <td>
            	<a href="http://www.zendframework.com/apidoc/2.3/classes/Zend.Stdlib.ArrayUtils.html#merge">
                ArrayUtils::merge</a>
            </td>
        </tr>
    </tbody>
</table>
<h5 id="examples">Examples</h5>
<p>Like numeric keys, the <code>+</code> operator always drops duplicates found in the right operand.</p>
<pre><code class="language-php">['foo' =&gt; 1] + ['foo' =&gt; 2];
</code></pre>
<blockquote>
<p>['foo' =&gt; 1]</p>
</blockquote>
<p>For string keys, <code>array_merge</code> drops duplicates found in the first argument.</p>
<pre><code class="language-php">array_merge(['foo' =&gt; 1], ['foo' =&gt; 2]);
</code></pre>
<blockquote>
<p>['foo' =&gt; 2]</p>
</blockquote>
<p><code>array_merge_recursive</code> preserves duplicates by pushing each value into a new array under the duplicate key.</p>
<pre><code class="language-php">array_merge_recursive(['foo' =&gt; 1], ['foo' =&gt; 2]);
</code></pre>
<blockquote>
<p>['foo' =&gt; [0 =&gt; 1, 1 =&gt; 2]]</p>
</blockquote>
<h4 id="precedence">Precedence</h4>
<p>The argument for which duplicate keys are kept is said to have <em>precedence</em> during a merge. Argument order determines which values are <strong>kept</strong> and which are <strong>lost</strong> during replacement.</p>
<p>The <code>+</code> operator gives precedence to the <strong>first operand</strong> but the other merge functions give precedence to the <strong>second argument</strong> as shown in the table below. Argument order for <code>array_merge_recursive</code> is usually irrelevant since it always appends duplicates.</p>
<table>
	<tr>
    	<th>Function or operator
        </th><th>Precedence
    </th></tr><tr>
    	<td><a href="http://www.php.net/manual/en/language.operators.array.php">+</a>
        </td><td>1<sup>st</sup> operand
    </td></tr><tr>
    	<td><a href="http://php.net/manual/en/function.array-merge.php">array_merge</a>
        </td><td>2<sup>nd</sup> argument
    </td></tr><tr>
    	<td><a href="http://www.zendframework.com/apidoc/2.3/classes/Zend.Stdlib.ArrayUtils.html#merge">
                ArrayUtils::merge</a>
        </td><td>2<sup>nd</sup> argument
</td></tr></table>
<h2 id="conclusion">Conclusion</h2>
<p>To merge two arrays correctly we must consider the data structure of each array and how we want to handle conflicts that occur when both arrays contain the same key. Once we know the data structure and have chosen a duplicate handling strategy we can select the correct function to merge our arrays.</p>
<p>Finally we ensure our arguments are specified in the correct order to give precedence to the array whose data we wish to keep when conflicts occur.</p>
</div>]]></content:encoded></item></channel></rss>