0

I would like to use the value of variable inside of a function, within another function that relies on this value.

For example:

function fetch_data($connect)
{
    $query = "SELECT Customer, Number, Serial
              FROM Table1 
              WHERE customer = 'Example'  ";

    $statement = $connect->prepare($query);
    $statement->execute();
    $result = $statement->fetchAll();
    $rowCount = $statement->rowCount();
    $output = '
    <div class="row">
    </div>
    <div class="table-responsive">
        <table class="table table-striped table-bordered">
        <br>
            <tr>
                <th>Customer</th>
                <th>Number</th>
                <th>Serial</th>
            </tr>
    ';
    foreach($result as $row)
    {
        $output .= '
            <tr>
                <td>'.$row["Customer"].'</td>
                <td>'.$row["Number"].'</td>
                <td>'.$row["Serial"].'</td>
            </tr>
        ';
    }
    $output .= '
        </table>
    </div>
    ';
    //return $output;
    return [ 'output' => $output, 'rowCount' => $rowCount ];
}

I am trying to use this value of $rowCount outside of this function, in another function elsewhere but cannot seem to understand how this is done. To pass the value of this variable from one function to another I am trying to use an array because I also have the variable $output to return.

The issue I am having is $output cannot be returned as an array (because of how some of the othersr functions are set up) while $rowcount can.

What is another way I can return both variables at once.

Ultimately I just need a way to share $rowcount between a few functions.

John
  • 965
  • 8
  • 16
  • As well as passing back an array, you can pass by reference - [this](https://stackoverflow.com/a/3579928/1213708) answer shows how to do that. – Nigel Ren Apr 06 '20 at 06:20
  • 1
    This function is just a terrible idea. it should return just a fetched array. Then, some other function should render this array as HTML. and instead of rowcount you should just use count($array); – Your Common Sense Apr 06 '20 at 06:32
  • 1
    @NigelRen a function that needs to return two results is already a bad design. And returning by reference is even worse, doing the same harm as using `global`, silently changing the value of a variable. – Your Common Sense Apr 06 '20 at 06:57
  • @YourCommonSense, equating by reference and `global` is something vastly different. By reference you are only going to be changing a variable directly passed to the function, not some random variable defined somewhere in the code. – Nigel Ren Apr 06 '20 at 06:59

0 Answers0