Page 2 of 2

Re: switch statement in php

Posted: Mon May 09, 2016 10:30 pm
by Christopher
Ok, that should work. You have the right idea. One thing I don't like is that the variable $transport starts with letter values, but you reassign it with a name. That is using a variable for two things, which is a good way to confuse yourself. Maybe you could make a function to get the name for a transport type.

Code: Select all

function transport_name($type)
{
	switch ($type){
		case 'A':
			$name ='Train';
			break;
		case 'B':
			$name ='Taxi';
			break;
		case 'C':
			$name ='Plane';
			break;
		case 'D':
			$name='Buses';
			break;
		case'E':
			$name='Motorbike';
			break;
		default:
			$name ='invalid Transport';
			break;
	}
	return $name;
}
            
$transport_list = array('A', 'B', 'C', 'D', 'E', 'F');
foreach ($transport_list as $transport) {        
	echo "$transport = " . transport_name($transport) . "<br>";
}