BigJazzz
BigJazzz

Reputation: 5

PHP can't get output from array

I posted a question last night that turned out to not be the problem. Digging around, I have discovered that the below code is giving me a headche. I had this working, but now for some reason I get no output. When I var_dump the function that gives me the $finishmins value, it outputs everything correctly until the point where it has to search the array (as below). After this it shows NULL. I was originally using strpos to find out if it started with a zero, then stripped said zero to match to the array, but when it stopped working, I tried the below approach to reduce code.

The point of the code is to convert minutes in time to minutes in decimal notation. I.e. 1 minute = 02, thus 12:01 = 12.02.

$finishmins = '01';
$finishmins = $minarray[$finishmins];

$minarray = array(
00 => '00',
01 => '02',
02 => '03',
03 => '05',
04 => '07',
05 => '08',
06 => '10',
07 => '12',
08 => '13',
09 => '15',
10 => '17',
'18',
// Array continues to 59 => '98'
);

echo $finishmins;

I have pasted the complete code here: http://codepad.org/EUW3n7AB and still can't seem to find the problem.

Upvotes: 0

Views: 45

Answers (2)

Ja͢ck
Ja͢ck

Reputation: 173542

There are two issues here:

  1. Array indices behave differently between strings and numbers,
  2. Variable scope of $minarray.

$arr[01] and $arr['01'] are not the same thing, so you should be more explicit; in your case you can just leave the array numerically indexed, i.e.:

$minarray = array('00', '02', '03', '05', ...);

Then, you use an (int) cast on the given minutes:

$finishmins = $minarray[(int)$finishmins];

You can solve the second issue by passing the array as a function argument:

function finishtime($minarray, $finish) 

Then calling it like so:

echo finishtime($minarray, '12:01');

Upvotes: 1

Lock
Lock

Reputation: 5522

You have to use the keyword global in your function when referring to the $minarray variable:

function finishtime($finish) {
    global $minarray;
    $finishx = explode(':', $finish);
    $finishhours = $finishx[0];
    $finishmins = $finishx[1];
    $finishmins;
    var_dump($finishmins);
    $finishmins = $minarray[$finishmins];
    var_dump($finishmins);

    $finishtime = $finishhours . '.' . $finishmins;

    return $finishtime;
}

Upvotes: 0

Related Questions