Gearing Man Gearing Man - 10 months ago 39
PHP Question

create image url with unlimited query strings

I have following

function where I pass parameters for each query string of the url. Sometimes I may require to add more query strings or less. How can my function can support unlimited url options? Should I add more arguments?

public function get_image_url($image_path, $width=null, $height=null, $cache=false){
$url = $this->get_image_path();

$image_path = $url.$image_path;

$image_path .= "&w=".$width;

$image_path .= "&h=".$height;

$image_path .= "&cache=1";

return $image_path;

Answer Source

You can send 1. image path and 2. query strings as associative array and then generate strings. You can try following:

public function get_image_url($image_path, $url_args=[]){
    $url = $this->get_image_path();

    $url_args = implode('&', array_map(function($k, $v){
            return sprintf("%s=%s", $k, $v);
        }, array_keys($url_args), array_values($url_args)));

        $url_args = '?'.$url_args;

    return $url.$image_path.$url_args;

you can call this function like get_image_url($image_path, ['w'=>100, 'h'=>100, 'cache'=>1])

Please let me know if it works and you need code explanation.