1

Is there util that parses array content without the need of iterating it and parsing each value?

input: ['2','3','7']

output: [2, 3, 7]

5
  • What? You mean turn string into integer or what? Commented Nov 2, 2016 at 20:38
  • @AbraCadaver yes, that's right Commented Nov 2, 2016 at 20:38
  • can we read a text without iterating by all letters? i don't think so. to do operations on array values there's always the need to iterating it. if you uses an function, this function will for sure itinerate through its values Commented Nov 2, 2016 at 20:41
  • 1
    @leo_ap Indeed. Wrong expression, pardon me Commented Nov 2, 2016 at 20:43
  • Why is this necessary? For most purposes where an int is needed, PHP will automatically handle the conversion anyway. Commented Nov 2, 2016 at 20:44

2 Answers 2

3

This obviously iterates internally, but you don't have to code an iterator:

$output = array_map('intval', $input);

Maps every value in $input to the intval() function and returns the result. For things that cannot be converted into an integer you'll get 0 or for objects, a notice and that value will not be returned.

I can't tell if you want to remove 0 values or not from your comment, but if so:

$output = array_filter(array_map('intval', $input));
Sign up to request clarification or add additional context in comments.

7 Comments

Can I hook to that fail convention 0 case? I might have valid zeros in the input
I don't know what you mean.
Do you mean remove 0 values???
ok my bad, understood
@JockyDoe See the PHP manual for the rules on string conversion to number. Keep in mind that strings with mixed letters/numbers will convert to nonzero numbers if they begin with nonzero numbers.
|
-1

You can use array_map

array = ["2","3","4"];

$intArray = array_map('intval', $array);

2 Comments

This is exactly the same as the other answer, but with no explanation.
@Jocky Doe :). It is always a benefit, to learn how functions work. So i added a link to the PHP Manual.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.