0

I am quite surprised that in the code below, the first var_dump outputs null while the second outputs the correct value (0.8215). How can I fix this ?

Looking at similar questions, this kind of problem seems to come from either :

-a too old version of php (as in here) but I'm using php 5.6.

-forgetting to put a return in a function (as in here or there), but I do have returns in my functions.

<?php

$ab_coefficients=array(
     1=>array( 0.9855 , 0.8678 ),
     2=>array( 0.9315 , 0.8215 )
);


function a_coefficient($k) {return($ab_coefficients[$k][0]);}
function b_coefficient($k) {return($ab_coefficients[$k][1]);}

var_dump($ab_coefficients[2][1]);
var_dump(b_coefficient(2));


?>
Community
  • 1
  • 1
Ewan Delanoy
  • 1,276
  • 2
  • 13
  • 31

2 Answers2

1

The problem is due to a scope issue. The $ab_coefficients array does not exist inside the functions as it is declared outside of them. A simple way to fix this is to include the line global $ab_coefficients; inside the functions as such:

function a_coefficient($k) {
    global $ab_coefficients;
    return($ab_coefficients[$k][0]);
}
function b_coefficient($k) {
    global $ab_coefficients;
    return($ab_coefficients[$k][1]);
}

This will make the variable available inside the function.

Maltronic
  • 1,782
  • 10
  • 21
1

your functions are in parallel scopes from the global scope, to fix this, you can do 1 of 2 things. either pass in the $ab_coefficients array to the functions, or you can tell the function to read that variable from the global scope.

Parameters: (better option)

<?php

$ab_coefficients=array(
     1=>array( 0.9855 , 0.8678 ),
     2=>array( 0.9315 , 0.8215 )
);


function a_coefficient($ab_coefficients, $k) {return($ab_coefficients[$k][0]);}
function b_coefficient($ab_coefficients, $k) {return($ab_coefficients[$k][1]);}

var_dump($ab_coefficients[2][1]);
var_dump(b_coefficient($ab_coefficients, 2));


?>

Global:

<?php

$ab_coefficients=array(
     1=>array( 0.9855 , 0.8678 ),
     2=>array( 0.9315 , 0.8215 )
);


function a_coefficient($k) {global $ab_coefficients;return($ab_coefficients[$k][0]);}
function b_coefficient($k) {global $ab_coefficients;return($ab_coefficients[$k][1]);}

var_dump($ab_coefficients[2][1]);
var_dump(b_coefficient(2));


?>
iam-decoder
  • 2,554
  • 1
  • 13
  • 28
  • Isn't it an exaggeration to say that the "parameters" version is always better ? In my project the "ab_coefficients" is intended to stay "global" and fixed all the time. Also, it seems a little silly to create a function that does such an infinitesimal job instead of simply not creating it and writing $ab_coefficients[$k][1] where it is needed. – Ewan Delanoy Nov 09 '15 at 06:56
  • [Why the Global State is Evil](http://programmers.stackexchange.com/questions/148108/why-is-global-state-so-evil) – iam-decoder Nov 09 '15 at 07:20
  • aah I'm starting to see your point ... thanks for the references – Ewan Delanoy Nov 09 '15 at 07:36