How to parse true and false string in an array to become booleans
arrays, boolean, php
Solution
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
Problem
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" ) ); ```