phpob-get-contents

How to use ob_get_contents with a function with arguments


I have a function like this:

function show_aval($place) {
//some function
}

I want to translate this into a variable so I do this:

ob_start();
show_aval(london);
$avalrooms = ob_get_contents();
ob_clean();

This will be fine if the argument is always "london" which is not. It may change to York or Manchester, etc. My question is what can I do in order to indicate the argument through the variable like this: $avalrooms["london"], $avalrooms["york"], $avalrooms["liverpool"], etc. without having to declare each variable one by one.

EDIT:

the code below:

ob_start();
show_aval(london);
$show_aval = ob_get_contents();
ob_clean();

ob_start();
show_aval(york);
$show_aval2 = ob_get_contents();
ob_clean();

ob_start();
show_aval(liverpool);
$show_aval3 = ob_get_contents();
ob_clean();

will work but its just too much code. I tried with foreach but that seems to get ob_get_contents nullified.


Solution

  • Put the cities in an array, loop over the array, and use them as the function argument and array index.

    $avalrooms = [];
    $cities = ["london", "york", "liverpool"];
    foreach ($cities as $city) {
        ob_start();
        show_aval($city);
        $avalrooms[$city] = ob_get_contents();
        ob_clean();
    }