D
D
Donald_Duck2018-07-16 11:54:53
PHPUnit
Donald_Duck, 2018-07-16 11:54:53

How to check if an array contains only integer or float values?

Hello!
I can not understand how this can be done for several types. assertContainsOnly()checks for only one type. I understand that this should be done with the help assertThat(), but I can’t figure out how to compose it correctly.
Let's say we have an array [28, 1, 7.3]. How to check that it definitely contains only values ​​of type integeror float?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Maxim Fedorov, 2018-07-16
@Donald_Duck

Crutch, but it works, I'm looking for a more elegant solution
Briefly - we generate an array of arrays from an array of values, each of which contains the type of elements of the initial array and iterate the test for each type, comparing with the required types
Note 1: the float type is the only one given as double: php .net/manual/ru/function.gettype.php
Note 2: If there are many values ​​in the array being checked, then you need to make the provider return only arrays with unique types

/**
     * @dataProvider providerTypesOfArraysElements
     */
    public function testTypeInArray($type)
    {
        $typesCorrect = ['integer', 'double'];
        $this->assertContains($type, $typesCorrect);
    }

    public function providerTypesOfArraysElements()
    {
        $arr = [28, 1, 7.3];

        return array_map(function($val) {
            return [gettype($val)];
        }, $arr);
    }

Screenshot of a successful
5b4c72b0aee63855546159.png
Screenshot of unsuccessful
5b4c75ba049b8949436369.png
Screenshot of unsuccessful
5b4c76202ce06299115373.png

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question