0

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

3 Answers 3

5

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"
}
Sign up to request clarification or add additional context in comments.

1 Comment

omg, thanks, I angryon myself wright now! Of course youre wright
4

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?

Comments

1

In_array function always returns false In this code statement - its does not add to array, just checks. That's why he is mistake.

2 Comments

is.php.net/in_array -> "Returns TRUE if needle is found in the array, FALSE otherwise."
indeed, missed that, got it back.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.