0

When I try to convert a number as a string to an integer, The value changes to 0.

I did a preg_match and picked out a number value which as an output of preg_match is in a string datatype.

That is, When i tried to extract the number 7123 in the following xml data, <Count> 7123 </Count> using preg_match, I got the value 7123 as a string. [Used gettype function]. When I am checking if its 0 or anyother value, I need to convert it to integer datatype just to compare the values farely. So i do intval("7123") or intval($count) to get the integer value. But when I echo the value, its 0. Read few blogs online and one said this type of a thing happens when the string value is non-printable. Can someone help me understand this and help me solve it?

0

1 Answer 1

2

It's very simple once you know how to convert a string to integer:

$str = "7123";
$val = (int) $str;

echo $val + 1;

result: 7124

This is not the only way to convert strings to integers, but it's been proven to be the fastest.

Sign up to request clarification or add additional context in comments.

16 Comments

Nope. It still gives me the same 0 as result
Change your regex pattern to this: preg_match("/(\d+).+\/Count>/i",$handle,$match1);
Okay, I see what is going on. Are you only trying to capture the first <count> value? also, post your code in your question next time.
Change your regex to this: preg_match_all("/<Count\D+(\d+)\D+\/Count>/i",$handle,$match1); — It will grab all values in an array, but you can use it just as you did before, with one slight change $totalcount=$match1[1][0];
You're missing a semi-colon after echo $match1[$i]; but since it's an array you need print_r($match1[$i]); you can also do print_r($match1[1]); without the loop, it gives the same result.
|

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.