开发者

Is it possible to cast to a boolean array in php?

I'm sending a PHP script data converted from JSON into serialised form by JQuery (see http://api.jquery.com/jQuery.ajax/). PHP interprets the POST data as one big associative array, which is awesome.

What I'm wondering is, is it possible to cast to a boolean array in PHP? And generally, whether you can cast to a typed array in PHP?

At the moment I have an array of booleans in JavaScript which is interpreted as an array of string in PHP. I'm 开发者_C百科guessing you can't cast in that way, as a PHP array can contain a mix of types?


Are you saying, you want to convert to something like:

array('TRUE', 'FALSE', 'TRUE', 'TRUE', 'FALSE');

to

array(TRUE, FALSE, TRUE, TRUE, FALSE);

?

Then, you could use something like this:

$a = array('TRUE', 'FALSE', 'TRUE', 'TRUE', 'FALSE');

function _str_to_bool($s) {
  return strtolower($s) == 'true';
}

$a2 = array_map('_str_to_bool', $a));

var_export($a2);
// array(true, false, true, true, false)

If you want to perform a "real" cast, instead (so, a string will evaluate to false only if == ""), just change the code in the callback function, to do a cast ((bool)$s in this case), or whatever you need.


Because post data is all strings your bool values are getting interpreted as strings. In this case you need iterate over the array and cast your values to bools, ex :

foreach($values as &$val)
    $val = (bool)$val;


PHP does not have a concept of a boolean array like Java does. "array" is a type, just as booleans, integers, and floats are types.

However, an array can contain boolean objects. You can use foreach to loop through an array and cast individual elements to boolean.

foreach ( $_POST as &$post_element ) {
    $post_element = (bool)$post_element;
}


PHP chooses the datatype as needed, you can force something into a specific datatype by specifying it like this:

$var = (bool) 1;

However why do you need to do the conversation? PHP will change the datatype according to the operation you perform.


You're right that PHP is dynamically typed. But you can still coerce/convert the types a little. If you know what the string for false and the string for true, you can do something like this, to coerce it into an array

foreach( $array as &$value ) $value = ($value === $trueStr);

(Edit: George or Adil's answers would work equally well, if the true/false string values are truthy/falsey values like "1" and "0", but if - for some reason - your array sends you "yes" and "no" instead, then (bool) $value will be true for both, as both are non-empty strings. This one does a strict comparison of the input and the true/false string values - if there's any doubt, a value will be false)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜