Gearing Man Gearing Man - 22 days ago 6
PHP Question

create image url with unlimited query strings

I have following

get_image_url()
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;

if(!empty($width)){
$image_path .= "&w=".$width;
}

if(!empty($height)){
$image_path .= "&h=".$height;
}

if($cache){
$image_path .= "&cache=1";
}

return $image_path;
}

Answer

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)));

    if(!empty($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.