Need help with stripping characters from numbers in array [message #181009] |
Fri, 05 April 2013 16:01 |
daveh
Messages: 18 Registered: March 2013
Karma: 0
|
Junior Member |
|
|
Hello
Given I have an array as such: (as an example)
Array ([0]=>+1.,[1]=>+2.,[2]=>-3.0,[3]=>A3B)
I want to return an array as such: Array ([0]=>1,[1]=>2,[2]=>3,[3]=>A3B)
basically if its a number remove leading + or - char from number and any decimal point but do not do anything with letters or anything with number and char combination such as 2B or A3 and so forth.
I can strip the numbers with this function:
$number = preg_replace("/[[:^digit:]]/", '', $number);
So basically I have to traverse an array element by element check if it is a number and if so strip it otherwise leave it alone and go to next and save the results into an array and the return that array. Or I can simply remove plus, minus or dot chars from every element. (that is all that I would need as that would cover every conceivable scenario)
Can someone suggest how to code this?
Thanks
|
|
|
Re: Need help with stripping characters from numbers in array [message #181010 is a reply to message #181009] |
Fri, 05 April 2013 17:43 |
Salvatore
Messages: 38 Registered: September 2012
Karma: 0
|
Member |
|
|
On 2013-04-05, daveh(at)allheller(dot)net <daveh(at)allheller(dot)net> wrote:
> So basically I have to traverse an array element by element check if it is a number and if so strip it otherwise leave it alone and go to next and save the results into an array and the return that array. Or I can simply remove plus, minus or dot chars from every element. (that is all that I would need as that would cover every conceivable scenario)
>
> Can someone suggest how to code this?
A foreach (key => value) loop?
--
Blah blah bleh...
GCS/CM d(-)@>-- s+:- !a C++$ UBL++++$ L+$ W+++$ w M++ Y++ b++
|
|
|
Re: Need help with stripping characters from numbers in array [message #181011 is a reply to message #181009] |
Fri, 05 April 2013 18:41 |
Christoph Becker
Messages: 91 Registered: June 2012
Karma: 0
|
Member |
|
|
daveh wrote:
> Given I have an array as such: (as an example)
>
> Array ([0]=>+1.,[1]=>+2.,[2]=>-3.0,[3]=>A3B)
>
> I want to return an array as such:
> Array ([0]=>1,[1]=>2,[2]=>3,[3]=>A3B)
>
> basically if its a number remove leading + or - char from number and
> any decimal point but do not do anything with letters or anything
> with number and char combination such as 2B or A3 and so forth.
You may consider to slightly rewrite the requirements:
If it's a number, strip superfluous details; otherwise leave it as it is.
This specification leads to the following implementation:
$elt = is_numeric($elt) ? floatval($elt) : $elt;
To return the modified array array_map() seems to be appropriate.
Please wrap your lines to a reasonable width (see e.g.
<http://www.softdevlabs.com/personal/Usenet101.html#LineWrap>). TIA.
--
Christoph M. Becker
|
|
|
|