Reputation: 389
I got problem with array, this is my code:
$random_string = array();
for($i=0;$i<10;$i++)
{
$zmienna = generatePassword();
//echo $zmienna;
if (in_array($zmienna, $random_string))
$random_string[$i] = $zmienna;
}
var_dump($random_string);
on screen i see olny
array(0) { }
What's wrong? Becouse I'm sure that generatePassword();
working well
Upvotes: 0
Views: 53
Reputation: 3333
In_array function always returns false In this code statement - its does not add to array, just checks. That's why he is mistake.
Upvotes: 1
Reputation: 10732
This code:
if (in_array($zmienna, $random_string))
$random_string[$i] = $zmienna;
Will add $zmienna
to $random_string
if it's already in there; since it's a blank array at the start of the code, it's never going to be added, so the array will stay empty.
Do you mean:
if (! in_array($zmienna, $random_string)) {
Which will add it if it's not already there?
Upvotes: 4
Reputation: 31131
This line fails.
if (in_array($zmienna, $random_string))
$random_string
is empty so $zmienna
will never be "in" it.
I think you might have meant to put a NOT operator in there? if it is not in the array, add it? If so:
if (!in_array($zmienna, $random_string))
Also, your array will skip some keys. You'll end up with something like
array(3) {
[0]=>
string(1) "a"
[2]=>
string(1) "b"
[4]=>
string(1) "c"
}
If you don't specify an index with $i
(just do $random_string[] = $zmienna;
), it'll do the keys automatically, so you get
array(3) {
[0]=>
string(1) "a"
[1]=>
string(1) "b"
[2]=>
string(1) "c"
}
Upvotes: 5