Page 1 of 1

[RESOLVED]Simple array_push not working as expected

Posted: Mon Jun 23, 2008 9:43 am
by hyder_m29
$arr_hour = ("8.00/0", "8.00/0", "2.00/0", "8.00/0", "2.00/0", "0/0", "2.00/0", "0/0", "2.00/0") ;

Code: Select all

// variables declared here so accessible outside function scope
 
$arr_hour_regular = array();
$arr_hour_overtime = array();
    
    
    // goes through each hour item and splits it into overtime and regular, then pushes them into their resp. arrays
    function splitHours($hour_item, $hour_key, $delim) {
    
        $arr_hour_splitted = explode ($delim, $hour_item);
        array_push ($arr_hour_regular, $arr_hour_splitted[0]);
        //$arr_hour_overtime[] = $arr_hour_splitted[1];
    }
    
array_walk ($arr_hours, "splitHours", "/");
    
print_r ($arr_hour_regular);
OUTPUT:

Array ( )


I can print $arr_hour_splitted inside the function and it displays what it's supposed to,
so it does go through the array_walk function just fine. But why is it not pushing the
the strings into the new array?

Re: Simple array_push not working as expected

Posted: Mon Jun 23, 2008 10:03 am
by Kieran Huggins
das manual, ya wrote: Note: If you use array_push() to add one element to the array it's better to use $array[] = because in that way there is no overhead of calling a function.
does that method produce the same problem?

Re: Simple array_push not working as expected

Posted: Mon Jun 23, 2008 10:13 am
by hyder_m29
Kieran Huggins wrote:
das manual, ya wrote: Note: If you use array_push() to add one element to the array it's better to use $array[] = because in that way there is no overhead of calling a function.
does that method produce the same problem?
Yes it does, I'd read the exact same line while searching for a solution :D

Re: Simple array_push not working as expected

Posted: Mon Jun 23, 2008 6:22 pm
by hyder_m29
** BUMP **

C'mon guys, it really shouldn't be so hard to figure out!

Re: Simple array_push not working as expected

Posted: Mon Jun 23, 2008 7:00 pm
by Benjamin
Your variable isn't available inside the function.

Re: Simple array_push not working as expected

Posted: Mon Jun 23, 2008 7:38 pm
by hitman6003
As astions said, the $arr_hour_regular variable is not accessible from inside the function. This is called scope.

http://www.php.net/language.variables.scope

Re: Simple array_push not working as expected

Posted: Mon Jun 23, 2008 7:55 pm
by hyder_m29
astions and hitman, thanks guys

that actually makes sense... for some reason, i thought the function was part of the container!

Re: [RESOLVED]Simple array_push not working as expected

Posted: Mon Jun 23, 2008 9:03 pm
by Kieran Huggins
DOH :banghead:
Good catch astions!

Re: [RESOLVED]Simple array_push not working as expected

Posted: Mon Jun 23, 2008 9:36 pm
by Benjamin
Kieran Huggins wrote:Good catch astions!
Thanks Kieran, I'm pretty good at spotting errors.