Search code examples
phparraysbooleanreturn-typecustom-function

How to Call Function inside Array


I will create a json file with PHP with json_encode. I intend to include a function that I will call inside array before I change it to json. Whether calling functions inside an array can be done?

$arrayList = array( 
                array( 
                'uid' => "1234",
                'nilai' => getBoolean (1)));                
function getBoolean ($value) {
    if ($value == 0 ) {
        echo "false";
    } else {
        echo "true";
    }   
}
echo json_encode ($arrayList);

Output json

true[{"uid":"1234","nilai":null}]

What if I want json output like below

[{"uid":"1234","nilai":true}]

So the value of the function (getBoolean) goes into json not outside. Thanks


Solution

  • PHP uses an applicative order evaluation strategy so getBoolean(1) will be evaluated before the array is assigned to $arrayList.

    However, you have a bug in your getBoolean function. You need to return a boolean type value, not the string version of the boolean.

    Code: (https://3v4l.org/AOdn3B)

    $arrayList = [ [ 'uid' => '1234', 'nilai' => getBoolean (1) ] ];
    
    function getBoolean ($value) {
        return (bool) $value;
    }
    
    echo json_encode ($arrayList);
    

    Output:

    [{"uid":"1234","nilai":true}]
    

    p.s. I wouldn't personally bother to write a custom function for this. Just prepend (bool) directly to your array value.

    $arrayList = [ [ 'uid' => 1234, 'nilai' => (bool) 1 ] ];
    

    Then again if you have negative numbers or some other fringe case, use:

    if ($value == 0) {
        return false; // boolean, not string
    } else {
        return true; // boolean, not string
    }