Don't use if else ladder in php rather use this method

In this tutorial we will learn about php if statement multiple conditions example. When we develop application, sometimes we will face such situation that we need multiple if condition in php. That time normally we use if else ladder in php.

See the below example to understand if else ladder in php.

function get_array_data( string $type = null )
{

	if( $type == "apple" ) 
	{
		return "this is apple";
	}
    else if( $type == "cow" )
    {
    	return "this is cow";
    }
    else if( $type == "milk" )
    {
    	return "this is milk";
    }
    else 
    {
    	return "Not valid type";
    }
}

echo get_array_data('cow');

 

Output of this program will be this is cow.  Look this code pattern is so ugly i think. It looks very ugly in our code file. But we can easily avoid this code style with php associative array to get this same out put with php multiple condition.

See the below example where i won't use php if else ladder but it will work same with the same code.

function get_array_data( string $type = null )
{
	$typeArray = [

      'apple' => 'this is apple',
      'cow' => 'this is cow',
      'milk' => 'this is milk'

	];

	if (! array_key_exists( $type, $typeArray ) )
    {
     	 return "Not valid type";
    }

	return $typeArray[$type];

}

echo get_array_data('cow');

 

Output
this is cow

 

Look we don't need if else statement with multiple conditions in php rather we can write code using this method. It looks pretty well than before style. Hope it can help you.