I try to take elements from an array in php I have to check if the element is a string integer or a floating point number. Also, I have to display the result in a paragraph in the tree group the input is:
Bow
18
Alaska
4.5
France
1.5
10
13
45.1
The output is:
Group 1 – integers:
must be an integer
Group 2 – floats:
must be a float
Group 3 – strings
must be a string
My code is as follows it is totally wrong:
<?php
$elements = [];
while (FALSE !== ($line = fgets(STDIN))) {
$elements[] = trim($line);
}
foreach ($elements as $element) {
$data=(int)$element;
if($data>0){
print "<p>"."integers: ".$data." ,"."</p>";
}elseif($data===0){
print "<p>"."strings: ".$element."</p>";
}
}
?>
2
Answers
Create an array with keys, like this:
$groups = ['floats'=>[], 'ints' => [], strings => []];
Use the
is_int
,is_string
functions in order to detect when a variable holds an specific data type.More info here: PHP Documentation
Because your input is text (and your are trimming each value), every
$element
will be a string. You will not be able to use standardis_int()
oris_float()
functions on these strings.It may be fastest to cast the strings as a numeric type, then recast it to a string, then check if the new value is the same as the original value.
Code: (Demo)