<?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; variable types</title>
	<atom:link href="http://albertfama.com/tag/variable-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>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.1</generator>
		<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) [...]]]></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 [...]]]></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>
		<item>
		<title>MySQL returns strings&#8230;or does it?</title>
		<link>http://albertfama.com/php/mysql-returns-stringsor-does-it/</link>
		<comments>http://albertfama.com/php/mysql-returns-stringsor-does-it/#comments</comments>
		<pubDate>Thu, 18 Oct 2007 14:04:25 +0000</pubDate>
		<dc:creator>Albert Fama</dc:creator>
				<category><![CDATA[MySQL]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Variables]]></category>
		<category><![CDATA[Types]]></category>
		<category><![CDATA[variable types]]></category>

		<guid isPermaLink="false">http://obnexus.net/?p=23</guid>
		<description><![CDATA[I noticed an interesting fact yesterday, which pertains to my original post MySQL returns strings (if you have not read this yet, please do). The PHP function mysql_num_rows(), which returns the number of rows in a result set, I assumed would return the number of rows as a string. Since field values are all returned [...]]]></description>
			<content:encoded><![CDATA[<p>I noticed an interesting fact yesterday, which pertains to my original post <a href="/php/mysql-returns-strings/" title="albertfama.com: MySQL returns strings">MySQL returns strings</a> (if you have not read this yet, please do).  The PHP function <a title="PHP Manual: mysql_num_rows" href="http://us3.php.net/mysql_num_rows" title="MySQL returns strings" >mysql_num_rows()</a>, which returns the number of rows in a result set, I assumed would return the number of rows as a string.  Since field values are all returned as strings and for the sake of consistency my initial thought was that this function would also return a string.</p>
<p>One of the first things you should learn as a developer (or human) is to never assume, so I checked the documentation, and to my surprise I was completely wrong, the number actually arrives in PHP as an INT type.</p>
<p>The MySQL C API function <a href="http://dev.mysql.com/doc/refman/5.0/en/mysql-num-rows.html" title="MySQL Manual: mysql_num_rows" >mysql_num_rows()</a> returns a <a href="http://dev.mysql.com/doc/refman/5.0/en/c-api-datatypes.html#id2713549" title="MySQL Manual: my_ulonglong" >my_ulonglong</a> value:</p>
<blockquote><p><a rel="nofollow" href="http://www.amazon.com/MySQL-Developers-Library-Paul-DuBois/dp/0672326736/ref=pd_bbs_sr_2/103-4441044-9682228?ie=UTF8&amp;s=books&amp;qid=1192635085&amp;sr=1-2" title="Amazon: MySQL - Paul DuBois" >MySQL &#8211; Paul DuBois</a><br />
my_ulonglong &#8211; A long integer type, used for the return value of functions that return row counts or other potentially large numbers, such as mysql_affected_rows(), mysql_num_rows(), and mysql_insert_id()&#8230;</p></blockquote>
<p>This information again had me looking through the documentation in the PHP manual and in fact <a href="http://us3.php.net/manual/en/function.mysql-insert-id.php" title="PHP Manual: mysql_insert_id()" >mysql_insert_id()</a> does return an INT type (or FALSE on failure).</p>
<p>I find it interesting that in certain situations the data type coming from the MySQL C API is actually representative of the content of the data and at other times it is not. Not that this gets us any closer to why field values are all returned as strings, but the plot does thicken.</p>
<p>If anyone can shed any light on this topic, or would like to put their own spin on things, please feel free to comment.</p>
<p>In the next couple of days I will write a post explaining how, as a PHP developer, I became interested in variable types, and why you should also.</p>

                            <div id="aspdf">
                                <a href="http://albertfama.com/wp-content/plugins/as-pdf/generate.php?post=23">
                                    <span>&nbsp;</span>
                                </a>
                            </div>
                        ]]></content:encoded>
			<wfw:commentRss>http://albertfama.com/php/mysql-returns-stringsor-does-it/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>MySQL returns strings</title>
		<link>http://albertfama.com/php/mysql-returns-strings/</link>
		<comments>http://albertfama.com/php/mysql-returns-strings/#comments</comments>
		<pubDate>Tue, 16 Oct 2007 22:44:48 +0000</pubDate>
		<dc:creator>Albert Fama</dc:creator>
				<category><![CDATA[MySQL]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Types]]></category>
		<category><![CDATA[variable types]]></category>
		<category><![CDATA[Variables]]></category>

		<guid isPermaLink="false">http://obnexus.net/?p=22</guid>
		<description><![CDATA[This is a feature I have run into a few times (specifically when writing the unit tests for the Mysql Package). I thought I would post my thoughts and hopefully others will be able to expand on the topic. When querying data out of MySQL into PHP, all values arrive in PHP as strings, even [...]]]></description>
			<content:encoded><![CDATA[<p>This is a <em>feature</em> I have run into a few times (specifically when writing the unit tests for the <a href="/packages/mysql-package/" title="albertfama.com: Mysql Package">Mysql Package</a>). I thought I would post my thoughts and hopefully others will be able to expand on the topic.</p>
<p>When querying data out of MySQL into PHP, all values arrive in PHP as strings, even if the MySQL column type is INT. This <strong>is</strong> documented behavior:</p>
<blockquote><p>
PHP Manual &#8211; <a href="http://www.php.net/manual/en/function.mysql-fetch-array.php"  title="PHP Manual - mysql_fetch_array">mysql_fetch_array</a>&#8230;<br />
Returns an array of strings that corresponds to the fetched row&#8230;
</p></blockquote>
<p>I understand that PHP is a loosely typed language, which means PHP will convert the string to an integer on the fly (if it is deemed appropriate); but my question is: Why do integers arrive in PHP as strings?</p>
<p>A little research into the topic shows that the integer to string conversion actually happens outside the scope of PHP and lies in the MySQL C API. The <a href="http://dev.mysql.com/doc/refman/5.0/en/mysql-fetch-row.html"  title="MySQL C API - mysql_fetch_row"> mysql_fetch_row()</a> function (within the C API) returns the data type <a href="http://dev.mysql.com/doc/refman/5.0/en/c-api-datatypes.html#id3008291"  title="MySQL C API - MYSQL_ROW">MYSQL_ROW</a>, which is defined as:</p>
<blockquote><p>
A type-safe representation of one row of data. It is currently implemented as an array of counted byte strings. (You cannot treat these as null-terminated strings if field values may contain binary data, because such values may contain null bytes internally.) Rows are obtained by calling mysql_fetch_row().</p></blockquote>
<p>I have asked in a few forums and chat rooms about this, but was never really able to get a definitive answer. Most people say that since PHP is loosely typed it doesn&#8217;t matter, which I cannot accept as an answer, especially since the MySQL C API is not used exclusively for loosely typed languages.</p>
<p>One theory I heard is that since the C API is used in many different languages for connecting to MySQL, the creators decided it would simply be easier to return all values as strings. This could possibly be the case, but I do not know of a common language which could not handle an integer.</p>
<p>Has anyone else looked into this topic before, or do you have the answer that has eluded me?</p>

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

