PHP, how can I produce a list of unique numbers?
I have some numbers which will be part of an sql query, like this...
152258, 152258, 152258, 152258, 152261, 152261, 152261, 152261, 152261, 152270,
152270, 152270, 152287, 152287, 152287, 152287
M开发者_开发问答y query is quite complex and the list is quite long and I need to produce a unique list of numbers, can I do this with a regex?
If not how ?
Here is how you can make your string have unique numbers: http://codepad.org/cziNtZOS
<?php
$myString = "152258,152258,152258,152258,152261,152261,152261,152261,152261,152270,152270,152270,152287,152287,152287,152287";
$array = explode(",",$myString);
$unique = array_unique ( $array );
$myUniqueString = implode(",",$unique);
echo $myUniqueString ;
?>
I was going to write a function for you, turns out PHP has one already: array_unique()
Edit: in any case, this is one of the alternative ways of doing it:
function uniquify_array($a)
{
$b = array(); // I wish I could write just $b = {};
foreach ($a as $i)
$b[$i] = $i;
return $b;
}
Note that this function works only with values, whereas the built-in array_unique()
preserves the keys in the original array.
Generate some set of numbers and then just use array_unique
function
$nums = array();
for ($i = 0; $i < $limit; $i++) {
$nums[] = rand() * 10000;
$nums = array_unique($nums);
}
Sultan
If you want a range of numbers use PHP's range() method
If you want a unique list of numbers, you can use PHP's rand() method
range() : http://php.net/manual/en/function.range.php
rand() : http://php.net/manual/en/function.rand.php
EDIT And as @RobertPitt points out, uniqid can be used for generating IDs as well : http://php.net/manual/en/function.uniqid.php
USE RANGE()
REFERENCE
精彩评论