smepie
smepie

Reputation: 509

php, how to treat arrays with floats inside?

example:

the following is correct?

$var = floatval($arr[2]) ;

"You cannot use floatval() on arrays..." maybe that's an old directive or how to edit...?

Upvotes: 1

Views: 6510

Answers (2)

deceze
deceze

Reputation: 522451

That quote from the manual (which BTW doesn't seem to exist in the current manual anymore) only means that you can't use floatval on values that are arrays, i.e.:

$foo = array();
$bar = floatval($foo);

Which, BTW, is not entirely correct, since it would produce either 1.0 or 0.0, depending on whether the array was empty or not.* It just doesn't make much sense. If you access a scalar value inside an array, that's not using "floatval on an array". I.e., this works perfectly fine:

$foo = array("42.1231");
$bar = floatval($foo[0]);

That's using the scalar value in $foo[0], whether that's in an array or not is irrelevant.


* The manual now clearly says Empty arrays return 0, non-empty arrays return 1. Maybe this behavior has changed?

Upvotes: 5

Landon
Landon

Reputation: 4108

you will need to traverse the array and perform the operation on each element:

foreach($arr as $id=>$elem){
  $arr[$id]=floatval($elem);
}

Upvotes: -2

Related Questions