abaracedo
abaracedo

Reputation: 1454

array_shift shows warning if the variable has a null or empty value

I'm working on a MVC project and i'm on the part to get the URL values, to get each param i use array_shift() and the documentation says this:

Returns the shifted value, or NULL if array is empty or is not an array.

In my code i have these lines:

        $arrParams = isset($_GET["params"]) ? explode("/", $_GET["params"]) : "";

        $controller = array_shift($arrParams);
        $action = array_shift($arrParams);
        $params = array_shift($arrParams);

If i access to mvc-project.local and i don't pass any param to the URL appears this message:

Warning: array_shift() expects parameter 1 to be array, string given in ... on line 12

Where is the problem?

Upvotes: 0

Views: 481

Answers (2)

Rhumborl
Rhumborl

Reputation: 16609

You are defaulting $arrParams to an empty string, so that is why you get a warning (note not an error) about it being passed a string. Just make it an empty array:

$arrParams = isset($_GET["params"]) ? explode("/", $_GET["params"]) : array();

Or a not so good solution is to suppress the warning with @:

$controller = @array_shift($arrParams);
$action = @array_shift($arrParams);
$params = @array_shift($arrParams);

Upvotes: 1

Sougata Bose
Sougata Bose

Reputation: 31749

Try this -

    $arrParams = isset($_GET["params"]) ? explode("/", $_GET["params"]) : array();

Or

    (array) $arrParams = isset($_GET["params"]) ? explode("/", $_GET["params"]) : "";

Or

    $controller = array_shift((array)$arrParams);
    $action = array_shift((array)$arrParams);
    $params = array_shift((array)$arrParams);

Upvotes: 4

Related Questions