M
M
Mesuti2020-04-20 23:06:21
PHP
Mesuti, 2020-04-20 23:06:21

How to generate a unique element with respect to an array?

I create keys using $unique = uniqid()

How to additionally check uniqid () with each key of the array and only if no matches are found, save to a variable?


Unsuccessfully trying to do a search through the array iteration

$arr = R::getAll('SELECT `key` FROM `itemscategory` WHERE `id_user` = 100'); 
$unique = "5e9dfcc49a460"; // существующий key 

if (array_key_exists($unique, $arr)) {
  $unique = uniqid();
} else {
  $reallyUniqueKey = $unique;
   echo $reallyUniqueKey;  // 5e9dfcc49a460
}

var_dump($arr);

array(4) {
  [0]=>
  array(1) {
    ["key"]=>
    string(13) "5e9dfcc295981"
  }
  [1]=>
  array(1) {
    ["key"]=>
    string(13) "5e9dfcc49a460"
  }
  [2]=>
  array(1) {
    ["key"]=>
    string(13) "5e9dfcc5b1ff8"
  }
  [3]=>
  array(1) {
    ["key"]=>
    string(13) "5e9dfcc637f75"
  }
}

Answer the question

In order to leave comments, you need to log in

3 answer(s)
S
scottparker, 2020-04-20
@Mesuti

if(!in_array($unique, $arr))
  $unique = uniqid();
else
  $reallyUniqueKey = $unique;

 echo $reallyUniqueKey;

S
Sergey Sokolov, 2020-04-20
@sergiks

You can search in an array like this:

if (0 === count(array_filter($arr, function($el) use ($unique) {return $el['key'] == $unique;}))) {
    // йее, уникальное!
} else {
    // нашлись с таким значением
}

Quick fix: add parameters: uniqid('', TRUE)
This will increase the "uniqueness" of the generated values ​​and the risk of repetition.
Solution "at random": generate and write to the database. Count the number of lines, and the number of lines with DISTINCT `key`- they will not match if there were repetitions.
paranoid android solution: loop. Generate, check, in case of non-uniqueness again, repeat. Set up a counter of failed attempts. Throwing an Exception with regret when exceeding 1 million failed attempts to create something unique.

F
FanatPHP, 2020-04-21
@FanatPHP

Oh my God.
Well, I wrote you how to do

$unique = "5e9dfcc49a460";
$arr = R::getAll('SELECT `key` FROM `itemscategory` WHERE `id_user` = ? and title = ?',[$user_id, $unique]);

Though yes, you don't know SQL. That villain who tells kids that one R::getAll() command is enough to create websites, and now they can do anything they want, and there is nothing else to learn, they should stick their head in the toilet.
But judging by the statement of the problem, in any case, you are doing some kind of hell. Not in the sense of implementation, but in the sense of the original task.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question