skip to Main Content

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


  1. 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

    Login or Signup to reply.
  2. Because your input is text (and your are trimming each value), every $element will be a string. You will not be able to use standard is_int() or is_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)

    $lines = <<<LINES
    Bow
    18
    Alaska
    4.5
    France
    1.5
    10
    13
    45.1
    LINES;
    
    $grouped = array_fill_keys(['int', 'float', 'string'], []);
    foreach (explode(PHP_EOL, $lines) as $element) {
        if ($element === (string) (int) $element) {
            $grouped['int'][] = $element;
        } elseif ($element === (string) (float) $element) {
            $grouped['float'][] = $element;
        } else {
            $grouped['string'][] = $element;
        }
    }
    var_export($grouped);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search