php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #44444 Error in array_unique when objects are values
Submitted: 2008-03-16 12:33 UTC Modified: 2008-03-16 12:48 UTC
From: pawel dot jacek dot matysiak at gmail dot com Assigned:
Status: Not a bug Package: Arrays related
PHP Version: 5.2.5 OS: Windows XP
Private report: No CVE-ID: None
 [2008-03-16 12:33 UTC] pawel dot jacek dot matysiak at gmail dot com
Description:
------------
I've encountered a problem when working with array of objects and using mentioned library function array_unique. It just doesn't work.

Reproduce code:
---------------
<?php
class Test
{
	public $x;
	public function __construct($x)
	{
		$this->x = $x;
	}
}
$temp[] = new Test(1);
$temp[] = new Test(1);
var_dump($temp);
$temp2 = array_unique($temp);
var_dump($temp2);
?>

Expected result:
----------------
I expected the function to return the array with only one object. It could return unchanged array but I think it would not make any sense.



Actual result:
--------------
error: Catchable fatal error: Object of class Test could not be converted to string in test.php on line 13

Patches

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2008-03-16 12:41 UTC] felipe@php.net
Says the documentation:
"array_unique() sorts the values treated as string at first, then will keep the first key encountered for every value, and ignore all following keys. It does not mean that the key of the first related value from the unsorted array will be kept."

"Note: Two elements are considered equal if and only if (string) $elem1 === (string) $elem2. In words: when the string representation is the same. The first element will be used."

Then, this isn't a bug.

<?php

class foo { 
	public function __toString() {
		return 'Hi';
	}
}

var_dump(array_unique(array(new foo, new foo)));

/*
array(1) {
  [0]=>
  object(foo)#1 (0) {
  }
}
*/
 [2008-03-16 12:48 UTC] pawel dot jacek dot matysiak at gmail dot com
My fault. Sorry.
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Thu May 02 21:01:31 2024 UTC