Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

convert PHP array values from string to integer

i am beginner in PHP. i used Curl and regex to get all the number with a certain pattern from an HTML table like this:

  preg_match_all("/<td>[0-9]{1,2}\.[0-9]{2}<\/td>/m",$result,$match);
  print_r($match);

This is the result array: ($match)

Array ( [0] => Array ( [0] => 10.00 [1] => 10.00 [2] => 10.00 [3] => 1.00 [4] => 12.00 ) )

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

All the values are strings, i need them as integers how to do that?
i tried this solution but it’s gives 0 as an integer
(was 10.00) is it because it’s an array inside array?

$test = $match[0][1];
$test2 = (int)$test;
echo $test2

>Solution :

You need a capture group for just the number. See:

preg_match_all("/<td>([0-9]{1,2}\.[0-9]{2})<\/td>/",'<td>10.00</td><td>22.33</td>',$matches);
foreach($matches[1] as $match){
    echo (int)$match; 
}

See https://3v4l.org/kL6rp

Although you are seeing:

Array ( [0] => Array ( [0] => 10.00 [1] => 10.00 [2] => 10.00 [3] => 1.00 [4] => 12.00 ) )

Your array really has HTML still in it, so it is:

 Array ( [0] => Array ( [0] => <td>10.00</td> [1] => <td>10.00</td> [2] => <td>10.00</td> [3] => <td>1.00</td> [4] => <td>12.00</td> ) )

casting that to an int won’t work. So capturing the inner value via regex is a better approach. Alternatively strip_tags could be used.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading