user4438328
user4438328

Reputation: 35

php output loop array with switch gettype() give strange result

I have an array

Array (
    [members] => Array (
            [name] => longtext
            [datum] => date
            [more] => Array (
                    [0] => a
                    [1] => b
            )
        )
    [viewable] => 1
    [hierarchical] => 1
)

and when i try to loop the subarray $array['members']

foreach( $array['members'] as $k => $v) {    
    switch( gettype( $v ) ) {
        case "boolean":
            echo "boolean";
        case "array":
            echo "array";
        case "string":
            echo "string";
    }    
}

i expect output like

string string array

Instead i get the result

string string array **string**

I cant understand where the 4th string is coming.

When i try

foreach($array['members'] as $k => $v) {
    echo gettype($v);
}

the result is correct. Can someone explain me that? I also tried to change a member of the array to another type because i thougt php will merge same membertypes inside of the array but it doesnt.

Greets

Upvotes: 1

Views: 289

Answers (2)

HorusKol
HorusKol

Reputation: 8696

You need a break statement in each your cases - otherwise you fall through:

foreach( $array['members'] as $k => $v) {    
    switch( gettype( $v ) ) {
        case "boolean":
            echo "boolean";
            break;
        case "array":
            echo "array";
            break;
        case "string":
            echo "string";
            break;
    }    
}

Upvotes: 1

Eddie
Eddie

Reputation: 26844

The reason why you are getting that error is that you don't have break; on your cases.

On the third array element, it goes to array but since there is no break, it also goes to string

Your loop should be something like:

foreach( $array['members'] as $k => $v) { 
    switch( gettype( $v ) ) {
        case "boolean":
            echo "boolean";
            break;
        case "array":
            echo "array";
            break;
        case "string":
            echo "string";
            break;
    }    
}

Doc: switch

Upvotes: 1

Related Questions