<?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>Albert Fama &#187; Types</title>
	<atom:link href="http://albertfama.com/category/php/variables/types/feed/" rel="self" type="application/rss+xml" />
	<link>http://albertfama.com</link>
	<description>Freelance Web Programmer - specializing in PHP &#38; MySQL</description>
	<lastBuildDate>Fri, 20 Nov 2009 16:06:31 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>More on Types&#8230;</title>
		<link>http://albertfama.com/php/more-on-types/</link>
		<comments>http://albertfama.com/php/more-on-types/#comments</comments>
		<pubDate>Fri, 02 Nov 2007 21:00:09 +0000</pubDate>
		<dc:creator>Albert Fama</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[Types]]></category>
		<category><![CDATA[Variables]]></category>
		<category><![CDATA[variable types]]></category>

		<guid isPermaLink="false">http://obnexus.net/?p=30</guid>
		<description><![CDATA[Since I have neglected my blog this week I decided to write a small continuation of the discussion on Types in PHP.
I was helping a fellow coder yesterday, and he was having problems with a simple comparison statement. The situation he found himself in was this: 
A $_POST value could either be 0 (zero) or [...]]]></description>
			<content:encoded><![CDATA[<p>Since I have neglected my blog this week I decided to write a small continuation of the discussion on <a href="/php/variable-types-why-care/" title="albertfama.com: Variable Types - Why Care?">Types in PHP</a>.</p>
<p>I was helping a fellow coder yesterday, and he was having problems with a simple comparison statement. The situation he found himself in was this: </p>
<p>A $_POST value could either be 0 (zero) or a text string. If  incoming value was 0 (zero) that meant a new record needed to be inserted in the database, if it was a text string then the record already existed in the database and needed to be updated. Consequently he wrote his comparison statement like this:</p>
<pre name="code" class="php">&lt;?php
&nbsp;
if ($_POST[&quot;id&quot;] == 0) {
&nbsp;&nbsp;&nbsp;&nbsp;//insert db record
}
else {
&nbsp;&nbsp;&nbsp;&nbsp;//update db record
}
&nbsp;
?>
</pre>
<p>Everything looked fine to him, but no matter what value was passed in the $_POST variable the comparison statement evaluated to TRUE, meaning a new record was inserted into the database.</p>
<p>If you want to check it out yourself run this code:</p>
<pre name="code" class="php">&lt;?php
&nbsp;
$_POST[&quot;id&quot;] = &quot;0&quot;;
&nbsp;
if ($_POST[&quot;id&quot;] == 0) {
&nbsp;&nbsp;&nbsp;&nbsp;echo &quot;insert db record / &quot;;
}
else {
&nbsp;&nbsp;&nbsp;&nbsp;echo &quot;update db record / &quot;;
}
&nbsp;
$_POST[&quot;id&quot;] = &quot;string of text&quot;;
if ($_POST[&quot;id&quot;] == 0) {
&nbsp;&nbsp;&nbsp;&nbsp;echo &quot;insert db record&quot;;
}
else {
&nbsp;&nbsp;&nbsp;&nbsp;echo &quot;update db record&quot;;
}
&nbsp;
?></pre>
<p>If you run the code above it will print: &#8216;insert db record / insert db record&#8217;.</p>
<p>Now this is a <em>bad</em> comparision to begin with, since all values coming from $_POST are a string of text; but that was not the problem he was experiencing. </p>
<p>Why does &#8220;string of text&#8221; equal zero in the second comparision statement?&#8230;. because of TYPES, of course. </p>
<p>In the both comparison statements we are comparing a string and an integer, since we did not use the Identical comparison operator (===), PHP converts the string to an integer before making the comparison. This means it is the same as casting the string as an integer then making the comparison; such as:</p>
<pre name="code" class="php">&lt;?php
&nbsp;
$_POST[&quot;id&quot;] = &quot;string of text&quot;;
$_POST[&quot;id&quot;] = (int)$_POST[&quot;id&quot;];
&nbsp;
if ($_POST[&quot;id&quot;] == 0) {
&nbsp;&nbsp;&nbsp;&nbsp;echo &quot;insert db record&quot;;
}
else {
&nbsp;&nbsp;&nbsp;&nbsp;echo &quot;update db record&quot;;
}
&nbsp;
?>
</pre>
<p>When casting &#8220;string of text&#8221; as an integer &#8220;string of text&#8221; becomes 0 (zero). Check it out:</p>
<pre name="code" class="php">&lt;?php
&nbsp;
$_POST[&quot;id&quot;] = &quot;string of text&quot;;
$_POST[&quot;id&quot;] = (int)$_POST[&quot;id&quot;];
&nbsp;
var_dump($_POST[&quot;id&quot;]);
&nbsp;
?>
</pre>
<p>The above code will print: &#8220;int(0)&#8221;.</p>
<p>So how do we get this comparison to evaluate as intended? We cannot use the Identical (===) comparison operator, because as I said before, everything coming from $_POST is a string. This means we would have the same problem in reverse. The comparison would always evaluate to FALSE, and it would attempt to update records that do not exist. What we need is for PHP to evaluate both operands as strings, this can be accomplished two ways. Either by placing quotes around the 0 (zero) making it a string, or casting the 0 (zero) as a string. Such as:</p>
<pre name="code" class="php">&lt;?php
&nbsp;
if ($_POST[&quot;id&quot;] == &quot;0&quot;) {
&nbsp;&nbsp;&nbsp;&nbsp;//insert db record
}
else {
&nbsp;&nbsp;&nbsp;&nbsp;//update db record
}
&nbsp;
if ($_POST[&quot;id&quot;] == (string)0) {
&nbsp;&nbsp;&nbsp;&nbsp;//insert db record
}
else {
&nbsp;&nbsp;&nbsp;&nbsp;//update db record
}
&nbsp;
?>
</pre>
<p>Personally I think the first example is more appropriate, if you want to compare 0 (zero) as a string just write it as a string. I simply provided the casting example because we have previously <a href="/php/variable-types-why-care/#casting" title="albertfama.com: Variable Types - Why Care? - casting">discussed casting</a>.</p>
<p>If you would like to know more about Types in PHP you can read my previous post: <a href="/php/variable-types-why-care/" title="albertfama.com: Variable Types - Why Care?">Variable Types &#8211; Why Care?</a> and follow the links at the bottom of the article.</p>

                            <div id="aspdf">
                                <a href="http://albertfama.com/wp-content/plugins/as-pdf/generate.php?post=30">
                                    <span>&nbsp;</span>
                                </a>
                            </div>
                        ]]></content:encoded>
			<wfw:commentRss>http://albertfama.com/php/more-on-types/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Variable Types &#8211; Why Care?</title>
		<link>http://albertfama.com/php/variable-types-why-care/</link>
		<comments>http://albertfama.com/php/variable-types-why-care/#comments</comments>
		<pubDate>Mon, 22 Oct 2007 02:19:08 +0000</pubDate>
		<dc:creator>Albert Fama</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[Types]]></category>
		<category><![CDATA[Variables]]></category>
		<category><![CDATA[variable types]]></category>

		<guid isPermaLink="false">http://obnexus.net/?p=24</guid>
		<description><![CDATA[We have all heard PHP is a loosely typed language. If you are unsure of the meaning of the term &#8220;loosely typed&#8221; the definition in the PHP manual states (at least for our discussion):
PHP &#8211; Manual
The type of a variable is usually not set by the programmer; rather, it is decided at runtime by PHP [...]]]></description>
			<content:encoded><![CDATA[<p>We have all heard PHP is a loosely typed language. If you are unsure of the meaning of the term &#8220;loosely typed&#8221; the <em>definition</em> in the PHP manual states (at least for our discussion):</p>
<blockquote><p><a href="http://www.php.net/manual/en/language.types.php"  title="PHP Manual: Types">PHP &#8211; Manual</a><br />
The type of a variable is usually not set by the programmer; rather, it is decided at runtime by PHP depending on the context in which that variable is used.</p></blockquote>
<p>In code terms this means that we do not have to define a &#8220;type&#8221; for each variable, we can simply give the variable a value and the PHP engine will determine (through context clues) what the variable type should be at that instant (runtime). Also a variable&#8217;s <em>type</em> may change any number of times during the execution of a script, as shown by this example:</p>
<pre name="code" class="php">
&lt;?php
//the variables are defined as strings
//(with quotes)
&nbsp;
$integer1 = &quot;50&quot;;
$integer2 = &quot;14&quot;;
&nbsp;
//we can use them
//in mathematical equations
&nbsp;
echo $integer1 + $integer2; //64
&nbsp;
//we can also treat them
//as strings and concatenate them
&nbsp;
echo $integer1 . $integer2; //5014
&nbsp;
//if we want to get fancy we can also use
//them as arrays, which actually comes in
//handy once in a while
&nbsp;
echo $integer1[0] + $integer2[0]; // 6
//**note if the variables were defined as
//integers this last example would not
//work**
?>
</pre>
<p>Given this information, most PHP developers (especially those who use PHP exclusively) simply forget about variable types and PHP does all the work for them. I was one of those developers until I read an article (unable to locate the link at the moment) about optimizing your PHP code. </p>
<p>In the article the benchmarks showed a significant improvement in processing time when using the <a href="http://www.php.net/manual/en/language.operators.comparison.php"  title="PHP Manual: Comparison Operators">comparison operators</a> Identical (===) and Not Identical (!==) as opposed to Equal (==) and Not Equal (!=).</p>
<p>**Please note I have no idea if this optimization still true, or ever was, but for our purposes it really does not matter.**</p>
<p>The difference between (Not) Identical and (Not) Equal is that PHP checks both the value and <strong>type</strong> of the two operands, meaning:</p>
<pre name="code" class="php">
&lt;?php
//integer1 is defined as a string
$integer1 = &quot;50&quot;;
&nbsp;
//integer1 is defined as an integer
$integer2 = 50;
&nbsp;
if ($integer1 == $integer2) {
&nbsp;&nbsp;&nbsp;&nbsp;echo &quot;Equal / &quot;;
}
else {
&nbsp;&nbsp;&nbsp;&nbsp;echo &quot;NOT Equal / &quot;;
}
&nbsp;
if ($integer1 === $integer2) {
&nbsp;&nbsp;&nbsp;&nbsp;echo &quot;Identical&quot;;
}
else {
&nbsp;&nbsp;&nbsp;&nbsp;echo &quot;NOT Identical&quot;;
}
?>
</pre>
<p>The above code will print &#8220;Equal / NOT Identical&#8221;. During the first comparison (equal), type is not taken into consideration so the string &#8220;50&#8243; is equal to the integer 50; but in the second comparison (identical), a string and an integer are not the same, hence not identical.</p>
<p>Obviously when you start comparing two values using the (Not) Identical operator, type becomes very important and a little challenging at first. You will inevitably forget to take into consideration variable types, and some code will simply not execute as you planned.</p>
<p>OK, so now that I have briefly explained types (string and integer) in PHP terms, the question remains, why do we care? Simply put: because it is part of PHP. If you just want to create scripts which randomly display quotes, email the contents of a form, or other small tasks then there really is no reason to get involved with types or <a href="http://www.php.net/manual/en/language.types.type-juggling.php#language.types.typecasting"  title="PHP Manual: Type Casting">type casting</a>; but since you are reading this post (and have made it this far) I will assume you are slightly more interested in creating larger projects and applications. If this is the case then you need to learn about all aspects of PHP and in tern you will then be able to write more complicated, efficient and stable code.</p>
<p>As a quick example: you should know that all data coming from $_POST and $_GET arrives in PHP as stings (actually an array of strings; kind of like field values from MySQL <img src='http://albertfama.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  ).  So if you would like to check that an incoming value is numeric, you could use the function <a href="http://us.php.net/is_numeric"  title="PHP Manual: is_numeric">is_numeric()</a> or <a href="http://us.php.net/manual/en/function.ctype-digit.php"  title="PHP Manual: ctype_digit">ctype_digit()</a>. Of course if you wanted to determine if a value is numeric one of the quickest and most efficient ways is to cast the value.</p>
<p><a name="casting"></a><br />
Since 99% of the time 0 (zero) is not a valid value for incoming numeric data you can simply cast the variable. If the value only contains non-numeric characters; when cast as an integer PHP will set the value to 0 (zero). If the value is entirely numeric or begins with a number the numeric portion is converted. For example:  </p>
<pre name="code" class="php">
&lt;?php
$id = (int)$_POST[&quot;id&quot;];
if (0 === $id) {
&nbsp;&nbsp;&nbsp;&nbsp;echo &quot;NOT Numeric&quot;;
}
else {
&nbsp;&nbsp;&nbsp;&nbsp;echo &quot;Numeric&quot;;
}
?>
</pre>
<p>*Note: When casting a value please be sure to cast the value to the correct type.</p>
<p>If you would like to learn more about Types and Casting, here are some links to sections of the PHP Manual:<br />
<a href="http://www.php.net/manual/en/language.types.php"  title="PHP Manual: Types">Types</a><br />
<a href="http://www.php.net/manual/en/language.types.type-juggling.php#language.types.typecasting"  title="PHP Manual: Type Casting">Type Casting</a><br />
<a href="http://www.php.net/manual/en/ref.var.php"  title="PHP Manual: Variable Handling Functions">Variable Handling Functions</a></p>

                            <div id="aspdf">
                                <a href="http://albertfama.com/wp-content/plugins/as-pdf/generate.php?post=24">
                                    <span>&nbsp;</span>
                                </a>
                            </div>
                        ]]></content:encoded>
			<wfw:commentRss>http://albertfama.com/php/variable-types-why-care/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
