Вопрос

I use the php command parse_ini_file to load the config of an application. Looking at the php documentation there is example, wehere it looks like, that numeric values are excepted, by using those without quotes ". So I used an init-file like that:

arr[] = 1
arr[] = 2
arr[] = "string"
integer_value = 3

Parsing that file with
$init = parse_ini_file('myConfig.ini',0); i get the following result (var_dump($init);):

array(2) {
  ["arr"]=>
  array(3) {
    [0]=>
    string(1) "1"
    [1]=>
    string(1) "2"
    [2]=>
    string(6) "string"
  }
  ["integer_value"]=>
  string(1) "3"
}

Is there a way to process integer values as integer, not as a string, to get the following result:

array(2) {
  ["arr"]=>
  array(3) {
    [0]=>
    int(1)
    [1]=>
    int(2)
    [2]=>
    string(6) "string"
  }
  ["integer_value"]=>
  int(3)
}
Это было полезно?

Решение

Documentation doesn't state anything about returning option values of corresponding type. In fact, they should be strings in common case. (But, if you want, you can check this implementation). Instead you can apply simple callback, for example, via array_walk_recursive():

$array = ["arr"=>["0", "1", "2"], "integer_value"=>"3", "float_value"=>"-0.5"];
array_walk_recursive($array, function(&$value, $key)
{
    if(is_numeric($value))
    {
        $value = (string)((int)$value)===$value
            ?(int)$value
            :(double)$value;
    }
});

-check this fiddle.

Другие советы

A bit old, but for whoever else comes here these days:

As of PHP 5.6.1, [the parameter $scanner_mode] can also be specified as INI_SCANNER_TYPED. In this mode boolean, null and integer types are preserved when possible. String values "true", "on" and "yes" are converted to TRUE. "false", "off", "no" and "none" are considered FALSE. "null" is converted to NULL in typed mode. Also, all numeric strings are converted to integer type if it is possible.

Source: http://php.net/manual/en/function.parse-ini-file.php

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top