Home > front end >  array_slice throws undefined constant error
array_slice throws undefined constant error

Time:12-03

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?

CodePudding user response:

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

  •  Tags:  
  • php
  • Related