0
<?php

/*ARRAY 1*/

$numbers = [];

while (count($numbers) < 100) {
    $numbers[] = random_int(1, 6);

}

implode($numbers);

echo "<b>Array nummer 1:</b> ";

foreach ($numbers as $number) {
    echo $number . " ";

}

echo "<br><br><b>Array nummer 2:</b> ";

/*ARRAY 2*/

$numbers2 = [];

while (count($numbers2) < 100) {
    $numbers2[] = random_int(1, 6);

}

implode($numbers2);

foreach ($numbers2 as $number2) {
    echo $number2 . " ";
}

/*ARRAY 3 is not right*/

echo "<br><br>";

print_r ($numbers+$numbers2);



?>

I am practising php now and i was wondering how to count up array's like this: array1 = 1,2,4; array2 = 3,6,8;

so array 3 must be = 4,8,12

I was searching online but couldn't find answers on this so that's why i am asking here.

3
  • 1
    I don't see a pattern with those numbers so I'm not sure this can be done so easily. Commented Jun 3, 2018 at 1:49
  • What does 1, 2, 4 and 3, 6, 8 have to do with 4, 8, 12? Commented Jun 3, 2018 at 2:12
  • 4,8, 12 is the sum of array1+array2 Commented Jun 3, 2018 at 2:14

1 Answer 1

1

I suspect you are trying to achieve this:

$numbers3 = array();
for ($i=0; $i < count($numbers) && $i < count($numbers2); $i++) { 
    $numbers3[] = $numbers[$i] + $numbers2[$i];
}

The + operator doesn't work like making the sum of the elements on both arrays.

The + operator (on arrays) returns the right-hand array appended to the left-hand array; for keys that exist in both arrays, the elements from the left-hand array will be used, and the matching elements from the right-hand array will be ignored. See: http://php.net/manual/en/language.operators.array.php

Also, the implode doesn't work by reference. The result of the implode should be assigned to a variables. The implode($numbers2); doesn't makes anything (it executes, but you don't save the result)

Sign up to request clarification or add additional context in comments.

1 Comment

Check with var_dump() what those variables contain. I edited the code to match the names of your variables. There may be a typo, not set or be of another type other than array.

Your Answer

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