Search code examples
phparraysfunctionreturncodeigniter-4

How to return more than 1 values at a time in php function


I built this php function,

function refs()
{
    
    $total_ref = "1111";

    $active_ref = "100";

        return ("refs") ? "$total_ref" : "";
    
}

Now, I want to return the total_ref and active_ref at the same time.... How do I return both as an array and call the array

if I have

return [
        'total_ref'  => $total_ref,
        'active_ref' => $active_ref
    ];

Then with $refs = refs();

how do I echo active_ref or total_ref


Solution

  • You can just return an associative array with the values.

    function refs()
    {        
        $total_ref = '1111';
    
        $active_ref = '100';
    
        return [
            'total_ref'  => $total_ref,
            'active_ref' => $active_ref
        ];
    }
    

    In order to echo the result of the function, you can access array elements by keys.

    $refs = refs();
    echo $refs['total_ref'];
    echo $refs['active_ref'];