Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php strange behaviour accessing array

Tags:

arrays

php

I have a function returning an array, called curPageURL. On my local apache, I accessed the return-value of the Page like this: $pageUrl = explode('?',curPageURL())[0]; it worked pretty fine. But on live it didn't work. It took me a lot of time to figure out, that the error was accessing the array.

This solved the issue:

$pageUrl = explode('?',curPageURL());
$pageURL = pageURL[0];


function curPageURL() {
        $pageURL = 'http';
        if (isset($_SERVER["HTTPS"]) && $_SERVER["HTTPS"] == "on") {$pageURL .= "s";}
        $pageURL .= "://";
        if ($_SERVER["SERVER_PORT"] != "80") {
            $pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
        } else {
            $pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
        }
        return $pageURL;
    }
  • Can anybody explain why?

  • Is it forbidden to access array index directly by function's return value? If so, Why did it worked at my localhost, but not at my live host?

like image 416
Karl Adler Avatar asked Apr 29 '13 07:04

Karl Adler


2 Answers

$pageUrl = explode('?',curPageURL())[0]; only available when php version >= 5.4

As of PHP 5.4 it is possible to array dereference the result of a function or method call directly. Before it was only possible using a temporary variable.

Your online host is below that version.

like image 192
xdazz Avatar answered Sep 19 '22 14:09

xdazz


You would need current() until you have PHP 5.4 that supports array dereferencing on function results.

$pageUrl = current(explode('?',curPageURL()));
like image 26
Ja͢ck Avatar answered Sep 19 '22 14:09

Ja͢ck