php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Doc Bug #62822 array_unique() - Confusing example
Submitted: 2012-08-15 00:27 UTC Modified: 2012-08-23 16:23 UTC
From: danielklein at airpost dot net Assigned:
Status: Not a bug Package: Documentation problem
PHP Version: Irrelevant OS:
Private report: No CVE-ID: None
View Add Comment Developer Edit
Welcome! If you don't have a Git account, you can't do anything here.
You can add a comment by following this link or if you reported this bug, you can edit this bug over here.
(description)
Block user comment
Status: Assign to:
Package:
Bug Type:
Summary:
From: danielklein at airpost dot net
New email:
PHP Version: OS:

 

 [2012-08-15 00:27 UTC] danielklein at airpost dot net
Description:
------------
---
From manual page: http://www.php.net/function.array-unique#refsect1-function.array-unique-examples
---
In the example code int(4) and string("3") are both the first and last versions of those values encountered!
<?php
$input = array(4, "4", "3", 4, 3, "3");
               ^       ^^^  ^     ^^^
$result = array_unique($input);
var_dump($result);
?>

It would be better written as
<?php
$input = array(4, "4", "3", "4", 3, 3);
$result = array_unique($input);
var_dump($result);
?>
or something else that shows it's the _first_ value that determines the type, not the last.


Patches

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2012-08-23 16:23 UTC] googleguy@php.net
It's neither the first nor last value that determines the type of anything here. 
PHP determines type based on context of 
the value. See http://php.net/language.types.type-juggling for details.

However, types are not being determined here. We're just discovering values and 
whichever value happens to be discovered 
first in the array -- that array key will be preserved.

The implementation of array_unique() is such that it will "keep the first key 
encountered for every value". This is 
already noted in the documentation in the Description section of array_unique at 
the top.

This is also why the resulting output from var_dump() in the examples shows that 
key's 0 and 2 are the remaining results.

array(2) {
  [0] => int(4)
  [2] => string(1) "3"
}

0 being the offset of the first element in the array, and 2 being the offset of 
the third element in the array.
 [2012-08-23 16:23 UTC] googleguy@php.net
-Status: Open +Status: Not a bug
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Thu Apr 18 23:01:27 2024 UTC