在PHP中将1/0值转换为YES / NO

时间:2015-08-25 16:06:22

标签: php boolean

我有一些变量,即$ tv,$ car,$ refrigerator,$ laptop和$ desktop,取值为0/1表示是否存在是/否。

有没有简单的方法将这些从1/0转换为YES / NO?

使下面容易的东西

<?php
 $tv = 1;
 $car = 0;
 $refrigerator = 1;
 $laptop = 1;
 $desktop = 0;

 if($tv == 1)
  $tv = "YES";
 else
  $tv = "NO";
 print($tv);


 if($car == 1)
  $car = "YES";
 else
  $car= "NO";
 print($car);

 //Repeat so on for refrigerator, laptop , desktop
?>

3 个答案:

答案 0 :(得分:2)

您可以编写一个函数,这样就不会一遍又一遍地重复代码。

function yesNo(&$value){
    $value = $value == true ? 'Yes' : 'No';
}

yesNo($car);
yesNo($tv);

答案 1 :(得分:2)

对于学习提议,使用带引用的函数对我来说似乎有点复杂。所以我决定尽可能在给定的代码上编写这个小例子而没有引用,但返回值并且没有类型转换。 10是整数而不是布尔变量。因此,我们将使用===比较运算符来避免类型杂耍:

<?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));

?>

如果你感到幸运,你也可以使用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));
}

?>

快乐的编码。

答案 2 :(得分:0)

skroczek的方法在一个数组中为我工作,但我必须更新到以下内容才能工作:

function numberToString($n)
{
    return $n == 1 ? 'YES' : 'NO';
}