Andrew Nevskiy Andrew Nevskiy - 5 months ago 14
PHP Question

php playing tricks when I send an "8" as an argument

I can't understand what the hack is going on with my code))) May be I just need more experience but... Let's get down to business:

I wrote a function which returns an array with some statistic data for my system, all I need is just to specify the arguments as Year, M, D. If I send something like

getStatData(2016,07,07)
- works fine, But just as i send something with a digit eight - it fails! eg.:
getStatData(2016,07,08)
Of course I have a file the fn requires, more over It works fine if a specify args as strings ('2016', '07', '08'); But this is ain't cool:D

The function:

function getStatData($y,$m,$d=false){
if(isset($y) && is_numeric($y) && isset($m) && is_numeric($m)){

$m=($m<10)? '0'.$m : $m;

if(isset($d)){
$d=($d<10)? '0'.$d : $d;
$y= 'days/'.$y;
$data = file_get_contents(STATDIR.'/'.$y.'/'.$m.'_'.$d.'.json');
}

else {
$data = file_get_contents(STATDIR.'/'.$y.'_'.$m.'.json');
}
return json_decode($data, true);
}
else return false;
}


Calling...

print_r(getStatData(2016,07,08)); //call with 08


ERROR: file_get_contents(core/statistic/days/2016/07_00.json): failed to open stream: No such file or directory

Answer

Pass arguments as string like print_r(getStatData('2016','07','08'));

As a side note use str_pad() function to format month and date to 2 digit value. Instead if isset($d) use if($d)

function getStatData($y,$m,$d=false){
    if(isset($y) && is_numeric($y) && isset($m) && is_numeric($m)){
        // use str_pad
        $m=str_pad($m, 2, '0', STR_PAD_LEFT);

        if($d){
            // use str_pad
            $d=str_pad($d, 2, '0', STR_PAD_LEFT);
            $y= 'days/'.$y;
            $data = file_get_contents(STATDIR.'/'.$y.'/'.$m.'_'.$d.'.json');
        }

        else {
            $data = file_get_contents(STATDIR.'/'.$y.'_'.$m.'.json');
        }
        return json_decode($data, true);
    }
    else return false;
}

print_r(getStatData('2016','07','08'));