How do I parse the true
and false
string in an array to become boolean if they exist?
For instance,
form
$config = array(
"allow_n" => "true",
"allow_m" => "false",
"say" => "hello"
);
to
$config = array(
"allow_n" => true,
"allow_m" => false,
"say" => "hello"
);
Is it possible?
EDIT:
Thanks guys for the help.
Sorry I forgot to clarify from the beginning - this case may happen in a multidimentinal array, for instance,
$config = array(
"allow_n" => "true",
"allow_m" => "false",
"say" => "Hello",
"php" => array(
"oop" => "true",
"classic" => "false"
)
);
To convert String to Boolean, use the parseBoolean() method in Java. The parseBoolean() parses the string argument as a boolean. The boolean returned represents the value true if the string argument is not null and is equal, ignoring case, to the string "true".
The easiest way to convert string to boolean is to compare the string with 'true' : let myBool = (myString === 'true'); For a more case insensitive approach, try: let myBool = (myString.
boolean a[]= new boolean[nums. length]; Arrays. fill(a, false); // this will help you fill array of boolean with false.
The boolean array can be used to store boolean datatype values only and the default value of the boolean array is false. An array of booleans are initialized to false and arrays of reference types are initialized to null.
you can use array_walk_recursive
to achieve this :
Example
$config = array (
"allow_n" => "true",
"allow_m" => "false",
"say" => "Hello",
"php" => array (
"oop" => "true",
"classic" => "false"
)
);
var_dump ( $config );
array_walk_recursive ( $config, function (&$item) {
if ($item == "true") {
$item = true;
} else if ($item == "false") {
$item = false;
} else if (is_numeric ( $item )) {
$item = intval ( $item );
}
} );
var_dump ( $config );
Output Before
'allow_n' => string 'true' (length=4)
'allow_m' => string 'false' (length=5)
'say' => string 'Hello' (length=5)
'php' =>
array
'oop' => string 'true' (length=4)
'classic' => string 'false' (length=5)
Output After
array
'allow_n' => boolean true
'allow_m' => boolean false
'say' => string 'Hello' (length=5)
'php' =>
array
'oop' => boolean true
'classic' => boolean false
foreach ($config as $k=>$v)
{
$low_v = strtolower($v);
if ($low_v == 'true')
$config[$k] = true;
else if ($low_v == 'false')
$config[$k] = false;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With