<?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>helpers &#8211; Blackbams Blog</title>
	<atom:link href="https://blog.blackbam.at/tag/helpers/feed/" rel="self" type="application/rss+xml" />
	<link>https://blog.blackbam.at</link>
	<description>development - digital arts - internet</description>
	<lastBuildDate>Sat, 19 Sep 2015 03:10:26 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.7.2</generator>
	<item>
		<title>PHP: Get rid of  &#8220;Notice: Undefined index .. in .. on line XXX&#8221; and undefined variable problems forever with this script</title>
		<link>https://blog.blackbam.at/2015/09/19/php-get-rid-of-notice-undefined-index-in-on-line-xxx-and-undefined-variable-problems-forever-with-this-script/</link>
					<comments>https://blog.blackbam.at/2015/09/19/php-get-rid-of-notice-undefined-index-in-on-line-xxx-and-undefined-variable-problems-forever-with-this-script/#respond</comments>
		
		<dc:creator><![CDATA[Blackbam]]></dc:creator>
		<pubDate>Sat, 19 Sep 2015 03:08:27 +0000</pubDate>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[Web Development]]></category>
		<category><![CDATA[custom script]]></category>
		<category><![CDATA[helpers]]></category>
		<guid isPermaLink="false">https://blog.blackbam.at/?p=2264</guid>

					<description><![CDATA[Probably every PHP developer in the world has already seen the following notice at least once: Notice: Undefined index: not_set in /home/.sites/../../../&#8230;php on line 1 It happens if accessing the key of an array which does not exist. There is a very similar problem with PHP objects: If you access a property of an object [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>Probably every PHP developer in the world has already seen the following notice at least once: </p>
<p><strong>Notice: Undefined index: not_set in /home/.sites/../../../&#8230;php on line 1</strong></p>
<p>It happens if accessing the key of an array which does not exist.</p>
<p>There is a very similar problem with PHP objects: If you access a property of an object in PHP you just get an empty string <strong>ever knowing if the property even existed</strong>. PHP does not even throw notices in this case.</p>
<p>Some examples:</p>
<pre lang="php">

//
$array = array("a","b","c");
echo $array[2]; // returns "c"
echo $array[3]; // returns nothing, notice undefined index

//
$_POST["my_field"]; // returns the value if submitted, or a notice if that value was not submitted

//
$obj = new stdClass();
$obj->a = "12";
$obj->b = "whatever";

echo $obj->a; // outputs string "12"
echo $obj->c; // outputs nothing, not even a notice just empty string

</pre>
<p>In order to enable save and good programming with PHP experienced PHP developers check for type safety and save array key accesses within their applications which usually requires a lot of extra work. PHP provides some operators and methods which check for the existence of keys and properties as well as for their type safety.</p>
<p>Example: Check if the user has submitted the value &#8220;yes&#8221; for the field &#8220;update&#8221; from a form and the array $_POST at key update contains a string value of yes.</p>
<pre lang="php">

if(isset($_POST['update']) &amp;&amp; $_POST['update'] === "yes")) {

}

</pre>
<p>Quite a lot of text to write right? There are a lot of native PHP methods which check for existence like isset(), property_exists(), array_key_exists() and more. Furthermore there are a lot of methods which check for type safety like is_int, is_bool etc. as well as the operators with the additional = like ===, !==.</p>
<p>However some time ago I somehow got annoyed by this behaviour of PHP especially. I developed a method which is especially useful in case a developer knows that a <strong>variable might not be populated</strong> and wants to set <strong>an adequate default value</strong> for this case. Furthermore I guarantees <strong>a type safe result</strong> for key/property access.</p>
<p>Just check out the following function and you may find it helpful, too:</p>
<p>&nbsp;</p>
<pre lang="php">
/**
 * Constats representing the primitive types.
 */
class Primitive {
    const STR = 0;
    const INT = 1;
    const BOOL = 2;
    const FLOAT = 3;
}

/**
 * In case you are unsure if an array key/object property exists and you want to get a (possibly typesafe) defined result.
 * 
 * @param $var array/object: An array or object with the possible key/property
 * @param $key array/string: The key. For a multidimensional associative array, you can pass an array.
 * @param $empty: If the key does not exist, this value is returned.
 * @param $primitive: The type of the given variable (-1 for ignoring this feature).
 * 
 * @return The (sanitized) value at the position key or the given default value if nothing found.
 */
function resempty(&$var,$key,$empty="",$primitive=-1) {
    
    $tcast = function($var,$primitive) {
        switch(true):
            case $primitive === Primitive::STR:
                $var = strval($var);
                break;
            case $primitive === Primitive::INT:
                $var = intval($var);
                break;
            case $primitive === Primitive::BOOL:
                $var = boolval($var);
                break;
            case $primitive === Primitive::FLOAT:
                $var = floatval($var);
                break;
        endswitch;
        return $var;
    };

    
    if(is_object($var)) {
        if(is_array($key)) {
            $tpclass = $var;
            $dimensions = count($key);
            for($i=0;$i<$dimensions;$i++) {
                if(property_exists($tpclass,$key[$i])) {
                    if($i === $dimensions-1) {
                        return $tcast($tpclass->$key[$i],$primitive);
                    } else {
                        $tpclass = $tpclass->$key[$i];
                    }
                } else {
                    return $tcast($empty,$primitive);
                }
            }
            return $tcast($empty,$primitive);
        }

        if(property_exists($var,$key)) {
            return $tcast($var->$key,$primitive);
        }
    } else if(is_array($var)) {
        if(is_array($key)) {
            $tpar = $var;
            $dimensions = count($key);
            for($i=0;$i<$dimensions;$i++) {
                if(array_key_exists($key[$i],$tpar)) {
                    if($i === $dimensions-1) {
                        return $tcast($tpar[$key[$i]],$primitive);
                    } else {
                        $tpar = $tcast($tpar[$key[$i]],$primitive);
                    }
                } else {
                    return $tcast($empty,$primitive);
                }
            }
            return $tcast($empty,$primitive);
        }

        if(array_key_exists($key,$var)) {
            return $tcast($var[$key],$primitive);
        }
    }
    return $tcast($empty,$primitive);
}

// Examples:
resempty($array,"key"); // returns the value at postion "key" if set, otherwise empty string
resempty($obj,"key",-1,Primitive::INT); // returns an integer value, -1 in case the property of the object is not set, otherwise the integer value of the object at this place


</pre>
<p>Be free to tell me if you find this useful or if you have improvement suggestions.</p>
<p><a class="a2a_dd addtoany_share_save addtoany_share" href="https://www.addtoany.com/share#url=https%3A%2F%2Fblog.blackbam.at%2F2015%2F09%2F19%2Fphp-get-rid-of-notice-undefined-index-in-on-line-xxx-and-undefined-variable-problems-forever-with-this-script%2F&#038;title=PHP%3A%20Get%20rid%20of%20%20%E2%80%9CNotice%3A%20Undefined%20index%20..%20in%20..%20on%20line%20XXX%E2%80%9D%20and%20undefined%20variable%20problems%20forever%20with%20this%20script" data-a2a-url="https://blog.blackbam.at/2015/09/19/php-get-rid-of-notice-undefined-index-in-on-line-xxx-and-undefined-variable-problems-forever-with-this-script/" data-a2a-title="PHP: Get rid of  “Notice: Undefined index .. in .. on line XXX” and undefined variable problems forever with this script"><img src="https://static.addtoany.com/buttons/share_save_120_16.png" alt="Share"></a></p>]]></content:encoded>
					
					<wfw:commentRss>https://blog.blackbam.at/2015/09/19/php-get-rid-of-notice-undefined-index-in-on-line-xxx-and-undefined-variable-problems-forever-with-this-script/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
