20. Session

What is a PHP Session?
The web server does not know who you are or what you do, because the HTTP address doesn’t maintain state. Session variables solve this problem by storing user information to be used across multiple pages (e.g. username, favorite color, etc). By default, session variables last until the user closes the browser.

So; Session variables hold information about one single user, and are available to all pages in one application.

Start a PHP Session
A session is started with the session_start() function.

Session variables are set with the PHP global variable: $_SESSION.



	echo isset($_SESSION['name'])?$_SESSION['name']." is available":"The user not Exist";

Destroy a PHP Session
To remove all global session variables and destroy the session, use session_unset() and session_destroy():


	echo isset($_SESSION['name1'])?$_SESSION['name1']." is available":"The user not Exist";

19. explode, array_slice, implode


	$test="This is our country, where are you come from?";
	$convert = explode(' ',$test);
	echo "<pre>";

	$slice = array_slice($convert,0,4);
	echo "<pre>";

	$conver_string = implode(' ',$slice);
	echo "<pre>";


Output following screenshot:

PHP extension is missing

|| New version magento 2 PHP Extension intl is missing   
1. Go to the file php.ini 
2. Search for ;extension=php_intl.dll
3. Remove semicolon and restart server. It will work.

|| Magento 1.4v-1.9.1 version 
1. Go to the file php.ini 
2. Search for ;extension=php_curl.dll
3. Remove semicolon and restart server. It will work.

Magento Code

|| How to remove the thousand separator in price
   Go to the folder lib/Zend/Local/Data/en.xml and Search <group> tag.
   Just do <group> </group> thousand separator as space, then cash clear

|| How To Remove Decimal format from price ?
   go to app/code/core/Mage/Directory/Model/Currency.php and change format function:

   public function format($price,$options=array(),$includeContainer = true,$addBrackets = false){   
      return $this->formatPrecision( $price,0,$options,$includeContainer,$addBrackets);

|| Recently viewed product

||  How to show out of stock in the product listing page
    1. First go to app/code/core/Mage/catelog/Block/product/list.php
    2. then find the function _getProductCollection()
    3. then find the following line

    $this->_productCollection = $layer->getProductCollection();
    modified this line, this following way
    $this->_productCollection = $layer->getProductCollection()->joinField('inventory_in_stock', 'cataloginventory_stock_item', 'is_in_stock', 'product_id=entity_id','is_in_stock>=0', 'left')->setOrder('inventory_in_stock','desc');

||  placing upsells in the product view page
     <block type="catalog/product_list_upsell" name="product.info.upsell" as="upsell_products" template="catalog/product/list/upsell.phtml">
          <action method="setColumnCount"><columns>5</columns></action>
          <action method="setItemLimit"><type>upsell</type><limit>5</limit></action>
     view page: <?php echo $this->getChildHtml('upsell_products'); ?>

||  page-title category-title
    catalog > category > view.phtml

||  get product price
    <div class="product_price">  
         <?php $_productCollection=$this->getLoadedProductCollection();
         $productBlock = $this->getLayout()->createBlock('catalog/product_price');
         echo $productBlock->getPriceHtml($_product); ?>

||  Configuring numbres of products displayed on the mini cart:
    System > Configuration > under Sales > Checkout > Shopping Cart Sidebar

||  How to enable/disable the demo store notice in Magento.
    System tab > Configuration > Design >  HTML Head > Display Demo Store Notice.
    notice text: page > html > notice.phtml

||  Proceed to Checkout

||  Header Top links 

||  To understand new order id:
    go > db Look in "eav_entity_store" and find increment_last_id.
    Change "increment prefix" to a name that could understood for new order id.

||  sales order view All Status in Admin Panel for Comments History:
    go to design/adminhtml/def/def/template/sales/oreder/view/history.phtml

    Replace :	
    <?php foreach ($this->getStatuses() as $_code=>$_label): ?>
    To :
    <?php foreach (Mage::getSingleton('sales/order_config')->getStatuses() as $_code=>$_label): ?>

||  remove white image frame:
    <li><a href="<?php echo $this->getProductUrl()?>" title="<?php echo $this->escapeHtml($this->getProductName()) ?>" class="product-image"><img src="<?php echo $this->getProductThumbnail()->keepFrame(false)->resize(45, 50)->setWatermarkSize('30x10'); ?>" width="45" height="50" alt="<?php echo $this->escapeHtml($this->getProductName()) ?>" /></a></li>

||  wishlist product image size location:

||  cart page product image size location:

||  Mini cart product image size location:

||  where is product category  title

||  How to product count:

<!-- total product count -->
    <?php $_helper = $this->helper('catalog/output'); ?>
    <?php $_category_detail = Mage::registry('current_category'); ?>
    <?php $_category_detail->getName(); ?>
    <?php $_category_detail->getId(); ?>
        $products_count = Mage::getModel('catalog/category')->load($_category_detail->getId())->getProductCount();
        echo'(' . ($products_count) . '&nbsp;' . 'Products Founds)';
    </p><!-- count end -->

||	how to set up mobile theme
	iPhone|iPod|BlackBerry|Palm|Googlebot-Mobile|Mobile|mobile|mobi|Windows Mobile|Safari Mobile|Android|Opera Mini

||	<?php echo $this->getChildHtml('topMenu') ?>
	<block type="catalog/navigation" name="catalog.topnav" template="catalog/navigation/top.phtml"/>
||   Product total view
	<div class="total_view">

			$id = $id=$_helper->productAttribute($_product, $_product->getId(), 'id');

			$fromDate = '2013-12-10';
			$toDate   = now();
			$viewedProducts = Mage::getResourceModel('reports/product_collection')->addViewsCount($fromDate, $toDate);
			foreach($viewedProducts as $product) {
				echo  "Total View Count: " . $product->getData('views');

||	Checkout page Button Place Order click then ajax loading title Submitting order information 

||	Edit was added to your shopping cart in magento 
	search this :  was added to your shopping cart.

||	Discount Codes

||	Product column count in xml page
	<action method="setColumnCount"><count>3</count></action>

||	How to Remove "Starting at" Price in Magento
	<span class="price-label"><?php echo $this->__('Starting at:') ?></span>

||	product view page compare & wishlist

||	product view page add to cart

||	Magento Currency Drop Down only Currency Symbols like BDT, USD >  template/directory/currency.phtml 
    <?php //echo $_name ?> <?php echo $_code ?>

||	Currency symbols from System->Manage Currency->Symbols.

||  Magento Currency Symbol 404's when i go to admin
    solve: Change line 68 in app\code\core\Mage\CurrencySymbol\etc\config.xml
    <currencysymbol before="Mage_Adminhtml">Mage_CurrencySymbol_Adminhtml</currencysymbol>

||	Currency:
	1.catalog.xml or page.xml
	   <block type="directory/currency" name="currency" as="currency" template="directory/currency.phtml"/>
	2.anywhere phtml file
	   <?php echo $this->getLayout()->createBlock('directory/currency')->setTemplate('directory/currency.phtml')->toHtml(); ?>

||  Currency remove: local.xml file
    <catalog_category_default><remove name="currency" /></catalog_category_default>

||	clear shopping cart & Update Shopping Cart is not working 
	---> In your /app/design/frontend/yourthemepackage/default/template/checkout/cart.phtml file or /app/design/frontend/default/yourtheme/template/checkout/cart.phtml file
		 Just place on line 50 just after getUrl('checkout/cart/updatePost') ?>" method="post"> paste the below code
		 <?php echo $this->getBlockHtml('formkey'); ?>

||	Login frontend edit

||	Checkout Login edit frontend (CHECKOUT AS A GUEST OR REGISTER)

||	Product url:
	<?php echo $_product->getProductUrl() ?>

||	name :
	<?php echo $this->__('Go') ?>

||	Default product image
	1. System > Configuration > Catalog > Product Image Placeholders
	2. skin\frontend\default\mytheme\images\catalog\product\placeholder

||	Adding Links to your topLinks

||	page > html >breadcrumbs.phtml

||	Only Contact Us page breadcrumbs:layout>contacts.xml
	<reference name="root">
	  <action method="unsetChild"><alias>breadcrumbs</alias></action>
		<block type="page/html_breadcrumbs" name="breadcrumbs" as="breadcrumbs">
			<action method="addCrumb">
			<action method="addCrumb">
			  <crumbInfo><label>Contact us</label><title>Contact us</title></crumbInfo>
	  <action method="setTemplate"><template>page/empty.phtml</template></action>
	  <action method="setHeaderTitle" translate="title" module="contacts"><title>Contact Us</title></action>

||	Breadcrumbs>page.xml:
	<label>Main Content Area</label>

||	Breadcrumbs Adding to cms pages in Magento:
	if ((!$crumbs || !is_array($crumbs)) && $this->getUrl('')!= $this->getUrl('*/*/*', array('_current'=>true, '_use_rewrite'=>true))) {
		$breadcrumb = $this->getLayout()->getBlock('breadcrumbs');
		$breadcrumb->addCrumb('home', array('label' => Mage::helper('cms')->__('Home'), 'title' => Mage::helper('cms')->__('Home Page'), 'link' => Mage::getBaseUrl()));
		$breadcrumb->addCrumb('my_account activeBreadcrumb', array('label' => $this->getLayout()->getBlock('head')->getTitle(), 'title' => $this->getLayout()->getBlock('head')->getTitle(), 'last' => 1));
		$crumbs = $breadcrumb->_crumbs;

||	Showing Breadcrums anywhere in Magento:
	<?php echo $this->getLayout()->getBlock('breadcrumbs')->toHtml()?>

||	if you want to condition that the slide show only home page:
        // If it is the home page, then just show up on the home page, other pages don't show 
	||  <?php if( Mage::getSingleton('cms/page')->getIdentifier()=='home') :?>
        <div class=""></div>    
		<?php endif;?>
	   // if it is the home page, then don't show up on the home page, other pages show up 
	||	<?php if(!(Mage::getSingleton('cms/page')->getIdentifier() == 'home'  && Mage::app()->getFrontController()->getRequest()->getRouteName() == 'cms')) : ?>

||	Short Description
	<?php echo $_helper->productAttribute($_product, nl2br($_product->getShortDescription()), 'short_description') ?>

||	Product Detail page Description
		$my_product = Mage::getModel('catalog/product')->load($_product->getId());
		echo $my_product->getDescription();

||	How to get attribute name and value?
	<p class="attribute"><?php echo "Author:".$attributeValue = Mage::getModel('catalog/product')->load($_product->getId())->getAttributeText('author');?></p>

||	One Page Checkout Success 2column
	---> app\design\frontend\default\default\layout\checkout.xml
		 <label>One Page Checkout Success</label>

||	Product Url
	<a href="<?php echo $_product->getProductUrl() ?>">Product Details</a>

||	Forgot Your Password? column layout->

||	Admin Change(xampp\htdocs\onlinesales\app\design\adminhtml\default\default\template)-
	1. login.phtml file:69 line
	2. forgotpassword.phtml file: 64 line
	<p class="legal"><?php echo Mage::helper('adminhtml')->__('Copyright &copy; FSB.', date('Y')) ?></p>

||	Search Bar Anywhere
	<?php echo $this->getLayout()->createBlock('core/template')->setTemplate('catalogsearch/form.mini.phtml')->toHtml();?>	

||	Advanced Search
	<a href="<?php echo $this->getUrl('catalogsearch/advanced/')?>"><?php echo $this->__('Advanced Search');?></a>

||	call name<li><a href="<?php echo $this->getUrl('');?>"><?php echo $this->__('Home');?></a></li>

||	media img src for phtml
	<img alt="author" src="<?php echo Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_MEDIA);?>/wysiwyg/author/Humayun-ahmed.jpg">

||	media img src for block:
	<a href="{{store url=''}}"><img src="{{media url='folder/sub1.jpg'}}" alt="" /></a>

||	page.xml:
	<block type="page/html" name="root" output="toHtml" template="page/3columns.phtml">

||	how to call topmenu.phtml in 2columns-left.phtml page
	<?php echo $this->getLayout()->createBlock('page/html_topmenu')->setTemplate('page/html/topmenu.phtml')->toHtml();?>

||	Diaplay SKU On The Product view Page:
	<p class="p_code">Product Code: <?php echo nl2br($_product->getSku()) ?></p>
	<?php echo $this->htmlEscape($_product->getSku()) ?>
	<?php echo $sku = Mage::getModel('catalog/product')->load($_product->getId())->getSku();?>

<-- Product Name call --->
<?php echo Mage::getModel('catalog/category')->load(20)->getName(); ?>

<-- Name & view more link-->
<?php $cate_id = 15; ?>
<h2><?php echo Mage::getModel('catalog/category')->load($cate_id)->getName(); ?> <a href="<?php echo Mage::getModel('catalog/category')->load($cate_id)->getUrl(); ?>"><?php echo $this->__('View More')?></a></h2>

||	product in phtml-page:
	<?php echo $this->getLayout()->createBlock('catalog/product_list')->setCategoryId(3)->setTemplate('catalog/product/list.phtml')->toHtml();?>

||	product in home page from Block
	{{block type="catalog/product_list" category_id="3" template="catalog/product/list.phtml"}}
	{{block type="catalog/product_list" column_count="4" category_id="45" limit="16" template="catalog/product/custom_scroll.phtml"}}

||	<?php $_columnCount = 4 //$this->getColumnCount(); ?>	

||	block call
	<?php echo $this->getLayout()->createBlock('cms/block')->setBlockId('opcontent')->toHtml() ?> 

||	cms page link:
	<div class="home_page">{{block type="core/template"template="page/home.phtml"}}</div>

||	catalog.xml>
	<!--Category default layout-->
	<!--Category layered navigation layout-->
	<action method="setColumnCount"><count>4</count></action>

||	no conflict jequry:
	$j = jQuery.noConflict();

||	Home page>phtml page link:
	<div class="custom_menu">
		<link rel="stylesheet" type="text/css" href="<?php echo $this->getSkinUrl('navigation/css/nav.css');?>" media="all" />
		<?php echo $this->getLayout()->createBlock('navigation/navigation')->setTemplate('navigation/left.phtml')->toHtml() ?>

||	compare:
	<?php echo $this->getLayout()->createBlock('catalog/product_compare_sidebar')->setTemplate('catalog/product/compare/sidebar.phtml')->toHtml();?>

||	show mycart in home page from block:
	{{block type="checkout/cart_sidebar" template="checkout/cart/sidebar.phtml"}}

||	mycart xml page
	<block type="checkout/cart_sidebar" name="checkout/cart_sidebar" template="checkout/cart/sidebar.phtml"/>		
||	Mycart:
	<?php echo $this->getLayout()->createBlock('checkout/cart_sidebar')->setTemplate('checkout/cart/sidebar.phtml')->toHtml();?>

||	Newsletter in phtml:
	<?php echo $this->getLayout()->createBlock('newsletter/subscribe')->setTemplate('newsletter/subscribe.phtml')->toHtml();?>
	<?php echo $this->getChildHtml('newsletter') ?>

||	show newsletter from block:
	{{block type="newsletter/subscribe" template="newsletter/subscribe.phtml"}}

||	Wishlist:
	<?php echo $this->getLayout()->createBlock('wishlist/customer_wishlist')->setTemplate('wishlist/sidebar.phtml')->toHtml();?>

||	Wishlist href link:
	<?php echo $this->helper('wishlist')->getListUrl()?> 

||	gaterthen code &gt; 

||	copyright code &copy;

||	Cart Count:
	<a href="<?php echo Mage::helper('checkout/cart')->getCartUrl(); ?>"> CART </a>
            <?php $cart=Mage::helper('checkout/cart')->getSummaryCount(); 
                if($cart == 0){
                    echo "0";
                    echo $cart;
||	Cart total amount 	
		$grandTotal = Mage::helper('checkout/cart')->getQuote()->getGrandTotal();
		$text = $this->__('%s', Mage::helper('core')->formatPrice($grandTotal, false));
	<span class="head_amount"><?php echo $text; ?></span>
||	Can I use multiple versions of jQuery on the same page?
	<!-- load jQuery 1.1.3 -->
	<script type="text/javascript" src="http://example.com/jquery-1.1.3.js"></script>
	<script type="text/javascript">
	   var jQuery_1_1_3 = $.noConflict(true);

	<!-- load jQuery 1.3.2 -->
	<script type="text/javascript" src="http://example.com/jquery-1.3.2.js"></script>
	<script type="text/javascript">
	   var jQuery_1_3_2 = $.noConflict(true);

||	mage media link magento:
	$media 	 = Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_MEDIA);
	$regFile = $media.'reg/regi.pdf';
	?><a href="<?php echo $regFile;?>">Download</a>

||	How to add related products tab in products detail page
		1.Go layout\catalog.xml
		search this> <block type="catalog/product_view_tabs" name="product.info.tabs" as="info_tabs" template="catalog/product/view/tabs.phtml" >
		2.<action method="addTab" translate="title" module="catalog"><alias>related</alias><title>Related Product</title><block>catalog/product_list_related</block><template>catalog/product/view/related.phtml</template></action>
		3.catalog\product\view>related.phtml page create and in this page <?php echo $this->getLayout()->getBlock('catalog.product.related')->toHtml()?> paste
		4.Related product image size (catalog\product\list\ralated.phtml)
		5.If you don't see output, you have to do must be cash refresh and logout

||	Display Related products in product details page:
	<?php //echo $this->getChildHtml('related'); ?>
	<?php //echo $this->getChildHtml('catalog.product.related') ?>
	<?php echo $this->getLayout()->getBlock('catalog.product.related')->toHtml()?>

||	Login & Logout:
		<?php if (Mage::getSingleton('customer/session')->isLoggedIn()==1): ?>
		<li class="first"><a title="Log Out" href="<?php echo $this->getUrl('customer/account/logout') ?>">Log Out</a></li>
		<?php else:?>
		<li class="first"><a title="Log In" href="<?php echo $this->getUrl('customer/account/login') ?>">Log In</a></li> | 
		<li class=""><a title="Register" href="<?php echo $this->getUrl('customer/account/create') ?>">Register</a></li> |
		<?php endif;?>
		<li><p>or create an<a href="<?php echo $this->getUrl('customer/account');?>">Account</a></p></li>

||	product onmouseover:
	<a href="<?php echo $_product->getProductUrl() ?>" title="<?php echo $this->stripTags($this->getImageLabel($_product, 'small_image'), null, true) ?>" class="product-image"><img src="<?php echo $this->helper('catalog/image')->init($_product, 'small_image')->constrainOnly(FALSE)->keepAspectRatio(TRUE)->keepFrame(true)->resize(192,224); ?>" width="192" height="224" alt="<?php echo $this->stripTags($this->getImageLabel($_product, 'small_image'), null, true) ?>" onmouseover="this.src='<?php echo $this->helper('catalog/image')->init($_product, 'thumbnail')->constrainOnly(FALSE)->keepAspectRatio(TRUE)->keepFrame(true)->resize(192,224) ?>';" onmouseout="this.src='<?php echo $this->helper('catalog/image')->init($_product, 'small_image')->constrainOnly(FALSE)->keepAspectRatio(TRUE)->keepFrame(true)->resize(192,224) ?>';" /></a>

||	Audio song added code:
	<div style="position:fixed; top:0; right:0; " class="auido_play">
		<audio loop="true" autoplay="autoplay" controls="controls">
			<source type="audio/wav" src="<?php echo $this->getSkinUrl('css/song.mp3');?>"></source>
	<embed src="<?php //echo $this->getSkinUrl('css/song.mp3');?>" autostart="true" loop="true"width="2" height="0"></embed> 
	<a href="<?php //echo $this->getSkinUrl('css/song.mp3');?>">Play music</a>

||	Online Visitor and Total Visitors in Magento:
	$visitor_count = Mage::getModel('log/visitor_online')->prepare()->getCollection()->count();
	if(!empty($visitor_count) && $visitor_count > 0)
		$cnt =  $visitor_count;
		echo 'Visitors online :'.$cnt;
	$write = Mage::getSingleton('core/resource')->getConnection('core_write');
	$readresult=$write->query("SELECT * FROM log_visitor ORDER BY visitor_id DESC LIMIT 1 ");
	while ($row = $readresult->fetch() )
		echo "Total Visitors".$row['visitor_id'];

||	Online Visitor from BBrands:
		 $visitor_count = Mage::getModel('log/visitor_online')->prepare()->getCollection()->count();
		 if(!empty($visitor_count) && $visitor_count > 0)
			echo $visitor_count.' Online Visitors'; 

Dynamic Menu

<!-----This is for All menu----->
$rootcatId= Mage::app()->getStore()->getRootCategoryId(); 
$categories = Mage::getModel('catalog/category')->getCategories($rootcatId);
function  get_categories($categories) {
    $array= '<ul>';
    foreach($categories as $category) {
        $cat = Mage::getModel('catalog/category')->load($category->getId());
        $count = $cat->getProductCount();
        $array .= '<li>'.
        '<a href="' . Mage::getUrl($cat->getUrlPath()). '">' . 
                  $category->getName() . "(".$count.")</a>\n";
        if($category->hasChildren()) {
            $children = Mage::getModel('catalog/category')->getCategories($category->getId());
             $array .=  get_categories($children);
         $array .= '</li>';
    return  $array . '</ul>';
echo  get_categories($categories); 
echo "<div class=\"clearer\"></div>";

<!------Only Current Menu > submenu-------->
<div class="left_menu">
		$routeDetect = Mage::app()->getFrontController()->getRequest()->getRouteName();
		if($routeDetect == 'catalog') :
	<div class="block block-whishlist">
		<div class="block-title">
			<strong><span>Current Categories</span></strong>
		<div class="block-content">
				$_current_category =Mage::registry('current_category')->getId();
				$collection = Mage::getModel('catalog/category')->getCategories($_current_category);
				$helper     = Mage::helper('catalog/category');	
				<?php foreach ($collection as $cat):?>
					<?php if($cat->getIsActive()):?>
						<li style="border-bottom: 1px solid #ddd">
							<a href="<?php echo $helper->getCategoryUrl($cat);?>">             
								<cite><?php echo $cat->getName();?></cite>
								$collection_sub = Mage::getModel('catalog/category')->getCategories($cat->getId());									
								<?php foreach ($collection_sub as $sub):?>
									<?php if($sub->getIsActive()):?>
										<li border-bottom: 1px solid #ddd>
											<a href="<?php echo $helper->getCategoryUrl($sub);?>">             
											&nbsp;<cite><?php echo $sub->getName();?></cite>
									<?php endif;?>
								<?php endforeach;?>	
					<?php endif;?>
				<?php endforeach;?>
	<?php endif;?>							
		$routeDetect = Mage::app()->getFrontController()->getRequest()->getRouteName();
		if($routeDetect != 'customer') :
	<?php endif;?>

Responsive Rules

<!--Quick Tip: Don't Forget the Viewport Meta Tag-->
<!--location head or header -->
<meta charset="utf-8"> 
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">

<!-- responsive start -->

// Small devices (landscape phones, less than 768px)
@media (max-width: 767.98px) { }

// Medium devices (tablets, 768px and up)
@media (min-width: 768px) { }

// Large devices (desktops, 992px and up)
@media (min-width: 992px) { }

// Extra large devices (large desktops, 1200px and up)
@media (min-width: 1200px) { }

// Super large devices (large desktops, 1400px and up)
@media (min-width: 1400px) { }

<!-- responsive end -->

18. Difference between GET and POST Request

Note that the query string (name/value pairs) is sent in the URL of a GET request:

Some other notes on GET requests:

  • GET requests can be cached
  • GET requests remain in the browser history
  • GET requests can be bookmarked
  • GET requests should never be used when dealing with sensitive data
  • GET requests have length restrictions
  • GET requests should be used only to retrieve data

Note that the query string (name/value pairs) is sent in the HTTP message body of a POST request:

POST /test/demo_form.asp HTTP/1.1

Some other notes on POST requests:

  • POST requests are never cached
  • POST requests do not remain in the browser history
  • POST requests cannot be bookmarked
  • POST requests have no restrictions on data length

17. isset and empty and Null

isset and empty are not actually regular functions but language constructs. That means they’re part of the PHP language itself.
bool isset( mixed $var [, mixed … ])
Returns true if the variable exists and is not null. Does not trigger an error if the variable does not exist.

	$foo = 'bar';
	var_dump(isset($foo));        //true

	$baz = null;
	var_dump(isset($baz));        //false

	var_dump(isset($undefined));  //false
if ($_GET['var'] == 'foo')

If $_GET[‘var’] actually exists, that is, if the URL contains ?var=foo, this will work just fine, regardless of the value of var. The presence or absence of $_GET[‘var’] is entirely in the hand of the user though. If the user does not include ?var=foo in the URL, this program will trigger an error.

To avoid this, we need to use isset:

if (isset($_GET['var']) && $_GET['var'] == 'foo')

isset can accept multiple arguments and only returns true if all of them are set:

if (isset($foo, $_GET['bar'], $array['baz'])) {
    // all needed values exist, do something with them

bool empty( mixed $var )
Returns true if the variable does not exist or its value equals false in a loose comparison. Does not trigger an error if the variable does not exist.

	$foo = 'bar';
	var_dump(empty($foo));        // false

	$baz = null;
	var_dump(empty($baz));        // true

	var_dump(empty($undefined));  // true

The important and remarkable thing about this behavior is that when trying to pass non-existent variables to normal functions, an error is triggered. PHP first tries to get the value of the variable, then pass it into the function:

  var_dump($foobar);   -> Notice: Undefined variable: foobar NULL

When talking about isset one inevitably must also talk about null. Let’s come back for a second to the predicament of PHP trying to skip over trivial errors without crashing a program.

	$foo = $_GET['var'];
	$bar = 'bar';
	if ($foo == $bar) {
		// do something

How should PHP behave in the above program if $_GET[‘var’] did not exist? Sure, it will throw a tantrum and trigger a notice, and that’s good and fine. But how should it treat $foo afterwards? As some sort of special outcast that doesn’t have a value? Should it trigger an error every time $foo is used hence? The answer is simple: PHP assigns the value null in place of the non-existent variable. null is a type unto its own. null is not a boolean, not an integer, not a string, not an object. null is of type null which can only have one value: null. null is used to mean the absence of a value, but null is just a regular value in itself. null loosely compares to false (null == false, but null !== false).