user2232681
user2232681

Reputation: 833

How to change array value from string to integer

I have the following array and I would like to change each [Entry] value from a string to an integer:

Array ( [0] => Array ( [Time] => 06:08:00 [Entry] => 250 ) [1] => Array ( [Time] => 08:08:00 [Entry] => 230 )

I am trying in this manner, which seems to change the type within the loop but the change does not seem to take effect outside the loop. I'm new at this, so I'm probably overlooking something, and most likely a simpler way to accomplish this.

foreach($data as $inner) {
foreach($inner as $key=>$val) {
    if($key == 'Entry') {
        $newval = intval($val);
        $val = $newval;
        echo(gettype($val));//integer
        }
    }
}

echo(gettype($data[0]['Entry'])); //string

Upvotes: 2

Views: 1136

Answers (2)

varun1505
varun1505

Reputation: 810

You are not changing the Value of the element in the array.

foreach($data as &$inner) {        
        $inner['Entry'] = intval($inner['Entry']);        
}

To modify the array elements within the loop, you have to precede $inner with &. i.e. The value will be assigned by reference.

For details see foreach

Upvotes: 2

Kenny
Kenny

Reputation: 1553

You need to re-cast it to the actual array.

foreach($data as $dkey => $inner) {
    foreach($inner as $ikey => $val) {
        if ($ikey == 'Entry') {
             $data[$dkey][$ikey] = intval($val);
        }
    }
}

Upvotes: 0

Related Questions