Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

array_slice throws undefined constant error

I am getting an array of ids from db, shuffling them and returning the first few elements:

    $stmt = $this->pdo->query("SELECT `id` FROM `IDS_TABLE` WHERE `active` = 1 LIMIT 10");
    $rows = $stmt->fetchAll();
    if($rows){
        $pageIdsArray = array_map(function($page){return $page["id"];}, $rows);
        shuffle($pageIdsArray);
        error_log(json_encode($pageIdsArray)); // looks ok
        $result = array_slice($pageIdsArray, 0, 3); // error here
        return $result;
    }

To my suprise,this code throws: PHP Fatal error: Uncaught ErrorException: Use of undefined constant \xc2\xa00 - assumed '\xc2\xa00' (this will throw an Error in a future version of PHP)

What am I doing wrong?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

There are two non-breaking space characters (u+00A0) before the 0 and the 3 in this line:

$result = array_slice($pageIdsArray, 0, 3); // error here

I’m guessing you may have copied this from a web page which inserted those characters for formatting.

Just retype it with regular spaces:

$result = array_slice($pageIdsArray, 0, 3); 

For future reference, some IDEs/editors like VS Code can be configured to give you a warning if such characters are present:
enter image description here

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading