0

I would like to do certain calculation in a function that takes a constant value against different values. To do that I created an array and a variable and also a loop that will take each member of the array and the constant value and pass them to the function that does the calculation. I would like to get an array and then I can do more calculations subsequently.

function subtract($a, $b){
    $c=$b-$a;
    return $c. ',';
    }
    $r=3;
$numbers = array(12, 11, 6, 9);

foreach ($numbers as $index=>$value) {
    $deductions=array(subtract($r, $value));
    //$minimum=min($deductions);
    if (is_array($deductions)){
    //echo $deductions;
    }else{
        //echo "not array";
    }
}
//$minimum=min($deductions);
//echo $minimum;
echo $deductions;

I get "Array" and not 9,8,3,6 Why is this? Any help is greatly appreciated. echo was partial problem, I get Array ( [0] => 6, ) not 9,8,3,6 as I expected?

The_Martian
  • 3,684
  • 5
  • 33
  • 61
  • 1
    you're outputting an array in string context, which becomes the literal word `Array`, e.g. `$foo = array('a'); echo $foo` will output `Array`, not `a`. If you want to spit out the array's contents, then `implode()` it to a string. – Marc B Jun 12 '15 at 21:16
  • This also makes no sense. your function returns a string. You wrap that string in an array, then check if you have an array. Of course it's always going to be an array - you just wrapped the array around the string on the previous line. – Marc B Jun 12 '15 at 21:18
  • Thanks everyone for pointing the "echo" issue, but I still have the other issue which is why I get 6 in index[0] when I am printing the whole result of the calculation in a nice array. That I don't get it. – The_Martian Jun 12 '15 at 21:39

3 Answers3

4

You cannot echo an array. Try using print_r($deductions) or var_dump($deductions).

Also, the following line is likely incorrect:

$deductions=array(subtract($r, $value));

This line will keep replacing the previous $deductions variable so you only end up with one value in your array (6) because 9-3 is 6. If you are wanting to create an array of values you need to add the new value to the array as follows:

$deductions[] = subtract($r, $value);
kojow7
  • 10,308
  • 17
  • 80
  • 135
  • 1
    @kowjow7, that did the trick. I wish I could give you 10 points but upvote and accept as an answer I all I can do for you. Thank you so much – The_Martian Jun 12 '15 at 21:50
  • @kowjow7, is $deductions[] now an actual array? Why can't I do the regular functions like sort, max, min stuff on it? – The_Martian Jun 12 '15 at 22:37
  • Yes, [] indicates an array. How exactly are you using those functions? You may want to post a new question with your code. – kojow7 Jun 12 '15 at 23:31
3

You can't echo an array. Use var_dump or print_r instead.

twentylemon
  • 1,248
  • 9
  • 11
3

You can also:

 for($i=0;$i<count($deduction);$i++)
 {
 $return += $deduction[$i]." ";
 }
 echo $return;