3

Possible Duplicate:
How to Convert Boolean to String

I think that asking this might be kind of silly but I'm still wondering whether there is built-in way to return false or true as they way they look instead of 0 or 1, well actually this code even doesn't write 0 but 1:

<?php
$array = array(1,2,3);
echo (bool) $array;
?>

So I want this code to write "true" or "false" instead of numeric values. I know I can build a function but my curiosity likes to learn a built-in way if there is any.

Community
  • 1
  • 1
Tarik
  • 79,711
  • 83
  • 236
  • 349

4 Answers4

7

Simply use the conditional operator:

echo (true ? 'true' : 'false');
echo (false ? 'true' : 'false');

Demo: http://codepad.org/hNHhXnBv

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
TimWolla
  • 31,849
  • 8
  • 63
  • 96
5

echoing a boolean will always print either 0 or 1. Instead, use var_dump().

Another option is to echo 'true' or 'false' based on the value:

echo ((bool)$array) ? 'true' : 'false'
Madara's Ghost
  • 172,118
  • 50
  • 264
  • 308
1

var_export() prints type and result.

echo var_export((bool)$array, 1);
powtac
  • 40,542
  • 28
  • 115
  • 170
0

I think the main problem is to convert the array ELEMENTS to booleans, not the array as a whole.

You could use the function array_map for this.

function conv2bool($i) { return (bool) $i; }

$int_array = array(0,1,0,2,3);
$bool_array = array_map("conv2bool", $int_array);

var_dump($bool_array);

...this will return:

array(5) { [0]=> bool(false) [1]=> bool(true) [2]=> bool(false) [3]=> bool(true) [4]=> bool(true) }
Mira Weller
  • 2,406
  • 22
  • 27