php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Doc Bug #80698 Add a note for key types may not be honored.
Submitted: 2021-02-02 19:13 UTC Modified: 2021-02-02 19:20 UTC
From: ksteinmetz at officesupply dot com Assigned:
Status: Not a bug Package: Arrays related
PHP Version: 7.4.14 OS: Ubuntu 18.04.5 LTS
Private report: No CVE-ID: None
 [2021-02-02 19:13 UTC] ksteinmetz at officesupply dot com
Description:
------------
---
From manual page: https://php.net/function.array-rand
---

As we are moving toward strong predictable typing, it would be nice to at least mention in the documentation that the quoted string integers would be implicitly converted to integers. Of course the fixes in our code are trivial. Type cast the results as needed or insure that the key really looks like a string to php. 

Test script:
---------------
is_string(array_rand(["1" => [2], "3" => [4], "5" => [6]]));
!is_string(array_rand([1 => [2], 3 => [4], 5 => [6]]));

Expected result:
----------------
true
true

Actual result:
--------------
false
true

Patches

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2021-02-02 19:20 UTC] requinix@php.net
-Status: Open +Status: Not a bug
 [2021-02-02 19:20 UTC] requinix@php.net
https://www.php.net/manual/en/language.types.array.php

> The key can either be an int or a string. The value can be of any type.
>
> Additionally the following key casts will occur:
> * Strings containing valid decimal ints, unless the number is preceded by a +
>   sign, will be cast to the int type. E.g. the key "8" will actually be stored
>   under 8. On the other hand "08" will not be cast, as it isn't a valid
>   decimal integer.
> * Floats are also cast to ints, which means that the fractional part will be
>   truncated. E.g. the key 8.7 will actually be stored under 8.
> * Bools are cast to ints, too, i.e. the key true will actually be stored under 1
>   and the key false under 0.
> * Null will be cast to the empty string, i.e. the key null will actually be
>   stored under "".
> * Arrays and objects can not be used as keys. Doing so will result in a warning:
>   Illegal offset type.
 
PHP Copyright © 2001-2021 The PHP Group
All rights reserved.
Last updated: Mon Sep 20 04:03:36 2021 UTC