For learning propose it seems a little to complicated to me to use a function with references. So I decided to write this little example as near as possible on the given code and without references, but return values and without typecasts.
1
and 0
are integers and not boolean variables. So we will use ===
comparison operator to avoid type juggling:
<?php
/**
* Convert number to 1 to'YES' or everything else to 'NO'.
* @param $n the number to convert.
* @return string YES|NO
*/
function numberToString($n)
{
return $n === 1 ? 'YES' : 'NO';
}
$tv = 1;
$car = 0;
$refrigerator = 1;
$laptop = 1;
$desktop = 0;
// Call numberToString function for $tv and print return value
print(numberToString($tv));
// Call numberToString function for $car and print return value
print(numberToString($car));
// Call numberToString function for $refrigerator and print return value
print(numberToString($refrigerator));
// Call numberToString function for $laptop and print return value
print(numberToString($laptop));
// Call numberToString function for $desktop and print return value
print(numberToString($desktop));
?>
And if you feel lucky you can also use array with foreach:
<?php
/**
* Convert number to 1 to'YES' or everything else to 'NO'.
* @param $n the number to convert.
* @return string YES|NO
*/
function numberToString($n)
{
return $n === 1 ? 'YES' : 'NO';
}
// For php >= 5.4 you can also use the new array syntax:
// $devices = [
// 'tv' => 1,
// 'car' => 0,
// 'refrigerator' => 1,
// 'laptop' => 1,
// 'desktop' => 0,
// ];
$devices = array(
'tv' => 1,
'car' => 0,
'refrigerator' => 1,
'laptop' => 1,
'desktop' => 0,
);
foreach ($devices as $device) {
// Call numberToString function for $tv and print return value
print(numberToString($device));
}
?>
Happy coding.