Razvan Zamfir
Razvan Zamfir

Reputation: 4614

Make an URL from a multidimentional array in PHP

I have the code below ment to turn an array into an url that has this form: $nopageurl = '/no/page/url?&value1=value2=&value3=&value4=';

foreach($_GET as $key => $value) {
    if(!in_array($key, array('page', 'a', 'sa', 'htaccess_key'))) {
        $nopageurl .= "{$key}={$value}&";
    }
}

But, the $_GET array has the form:

Array
(
 [value1] => 0
 [value2] => Array
    (
        [0] => 3113
        [1] => 3114
    )

 [value3] =>2
 [value4] =>status
);

And this causes the error E_NOTICE: Array to string conversion. What shall I do to avoid this error;

Upvotes: 1

Views: 133

Answers (2)

Ofir Baruch
Ofir Baruch

Reputation: 10346

As a developer you need to address all the possibilities regarding the INPUT from the user. You can restrict the input but then you need to validate it (don't allow sub-arrays for examples) or you need to address them and find a solution for those specific cases.

You need to consider the option that the a parameter also can be an array. Therefore, simply add a condition to check if the parameter is an array and if so, handle it as you wish. For example:

foreach($_GET as $key => $value) {
    if(!in_array($key, array('page', 'a', 'sa', 'htaccess_key'))) {
        if(is_array($key)){
           foreach($key as $k => $v){
             $nopageurl .= "{$key}[$k]={$v}&";
           }
        } else {
           $nopageurl .= "{$key}={$value}&";
        }
    }
}

Upvotes: 2

Razvan Zamfir
Razvan Zamfir

Reputation: 4614

Here is another valid way to do it:

foreach($_GET as $key => $value) {
    if(!in_array($key, array('page', 'a', 'sa', 'htaccess_key'))) {
        if(is_array($value)){
            foreach($value as $k => $v){
                $nopageurl .= "{$key}[$k]={$v}&";
            }
        } else {
            $nopageurl .= "{$key}={$value}&";
        }
    }
}

Upvotes: 0

Related Questions