Jump to content

How to create or make a set array in php?


colap

Recommended Posts

I could not agree more.

 

IMO, PHP's array is ambivalent of what it really is, i..e., it could be a set (no duplicates), list (no order, has duplicates), or ordered-list (has order, has duplicates). It depends on the context of its use.

 

I've tried to document it here:

http://www.reetudes.com/docs/latest/ch04.html#the-model-api.general-constructs.lists

 

As for creating a set in PHP, you can try re. re is an implementation the Relational Model of data.

Its basic data type is the relation, which is basically a set. Also, the usual set operators (i.e., UNION, JOIN/INTERSECT, MINUS, TIMES) are made available.

 

Hope it helps.

IMO, array_unique could not do the trick.

 

Consider:

$a = array(array(1), array(2));
print_r(array_unique($a)); //outputs array(0=>array(0=>1))

 

Clearly, $a has two elements which are themselves arrays: array(1) and array(2).

IMO, further, array_unique has a bug. It treats two distinct elements (in this case array elements) as equal!

I am not even sure what the original poster is looking for. But he said in the first post "does not contain duplicate values" so I thought array_unique might be helpful. Its also always possible to write your own function to modify data if there is not one that fits that purpose already in php.

Well, array_unique might do the trick for scalar elements.

 

But as for non-scalar elements, PHP has this disclaimer in the manual (I found out just now):

 

Note: Note that array_unique() is not intended to work on multi dimensional arrays. 

 

So, yes, array_unique would suffice for "simple sets" (i.e., sets who do not have nonscalar elements).

 

But as for sets that does have nonscalar elements, it is an entirely different story.

 

I hope PHP in the future will provide built-in set-theoretic operators and constructs.

Yeh, well you could make the nested arrays as one dimensional array and then run array_unique. But this is really up to that what kind of and output you really want. Might not work in all occasions.

 

// Function to flatten nested arrays.
function flatten_array($array,$return) 
{
for($x = 0; $x < count($array); $x++) 
{
	if(is_array($array[$x]))
	{
		$return = flatten_array($array[$x],$return);
	}
	else
	{
		if($array[$x])
		{
			$return[] = $array[$x];
		}
	}
}
return $return;
}

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.