-2

So I have the following array:

array:3 [
  0 => "6.05"
  1 => "5.94"
  2 => "5.96"
]

Which is passed through the following function:

$filteredShots = array_filter($shots, function($shot) {
        if (is_numeric($shot)) {
            return floatval($shot);
        }
});

Which then spits out, the exact same array:

array:3 [
  0 => "6.05"
  1 => "5.94"
  2 => "5.96"
]

Why are these still strings? I told it to convert them to floatval. Am I doing something wrong? Am I crazy?

If I die and dump on the return statement I get: 6.05, not "6.05" so ... why is the array reflecting that?

1 Answer 1

1

array_filter expects true or false from the callback function to retain or remove the corresponding element. In your implementation, unless you have a 0 or falsey value it will always return true. You want array_map that actually applies the return of the callback:

$filteredShots = array_map(function($shot) {
        if (is_numeric($shot)) {
            return floatval($shot);
        }
}, $shots);

You can also modify the original array using array_walk:

array_walk($shots, function(&$shot) {
        if (is_numeric($shot)) {
            $shot = floatval($shot);
        }
});

You can use array_filter to remove non-numeric:

$filteredShots = array_filter($shots, function($shot) {
        return is_numeric($shot) ? true : false;
});
//or simply
$filteredShots = array_filter($shots, 'is_numeric');
Sign up to request clarification or add additional context in comments.

1 Comment

@TheWebs That's what documentation is for, although the function names seem to describe what they do pretty clearly. Filtering means to reduce a collection to just the items that match some criteria.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.