-1

I'm trying to add to an array in a IF condition but it's not appending although i'm in a foreach loop

what I have doesn't append to $connected but the key increments:

$key1 = '0';
foreach ($dataNewAndUnlock1 as $key => $val) {
    $stream = ssh2_exec($connection, 'ping -c 1 '. $val);

    stream_set_blocking($stream, true);

    while ($o = fgets($stream)) {
        $connected = array();

        if (strpos($o, 'ttl') !== false) {
            $connected[$key1] = $val;

            echo $val .' EnodeB is connected <br>';
            $key1++;
        }

        if (strpos($o, '0 received') !== false) {
            echo $val .' EnodeB NOT connected <br>';
        }
    }
}

$connnected gives something like this, then var_dump is empty at the end

C:\wamp64\www\SendJason2.php:286:
array (size=1)
  0 => string 'XXX.XX.XXX.XXX' (length=14)
C:\wamp64\www\SendJason2.php:286:
array (size=1)
  1 => string 'XXX.XX.XXX.XX' (length=13)
C:\wamp64\www\SendJason2.php:286:
array (size=1)
  2 => string 'XXX.XX.XXX.XXX' (length=14)
C:\wamp64\www\SendJason2.php:286:
array (size=1)
  3 => string 'XXX.XX.XXX.XXX' (length=14)
C:\wamp64\www\SendJason2.php:286:
array (size=1)
  4 => string 'XXX.XX.XXX.XXX' (length=14)
...

C:\wamp64\www\SendJason2.php:306:
array (size=0)
  empty
3
  • 1
    Is the $val actually pushing data out? Commented Aug 6, 2018 at 15:38
  • Why do you initialize $key1 with the string 0 and then use $key1++? Commented Aug 6, 2018 at 15:42
  • Small note: Dont put your code in the C:\wamp64\www folder. Thats reserved for WAMPServer.. Make a subfolder for all your projects or better still a Virtual Host in a totally seperate folder Commented Aug 6, 2018 at 15:50

1 Answer 1

4

You are overwriting $connected with an empty array each time your foreach loop iterates. Move the assignment of $connected to before your foreach loop.

$key1 = '0';
$connected = array();
foreach ($dataNewAndUnlock1 as $key => $val) {
    ...

Also, to append to an array, you don't need to maintain your own index, you can just use this syntax:

$connected[] = $val;
Sign up to request clarification or add additional context in comments.

Comments

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.