user2556058
user2556058

Reputation: 311

What does (array) $variable mean in php

I'v recently came accross a problem with some code as shown below:

    $key = "upload_8_fid_aids.tmp";
    public function to_key($key) {

        $s = $this->table;//$s = kv
        foreach((array)$key as $k=>$v) {
            $s .= '-'.$this->primarykey[$k].'-'.$v;
        }
        return $s;
    }

There's a (array)$key signature out there in the foreach loop,the first thing I'm stucking in is the "array" that prefixed with the variabls $k,what does this mean?The very first idea that hit upon me is that it converts the $k to an array,though,the variable $k is a string,is it plausible to convert string to array in php?I think it is unreasonable.So what does that array mean?

Thanks in advance!

Upvotes: 0

Views: 149

Answers (3)

When you cast a string to an array in PHP it becomes an array with the string pushed to it.

Example:

$test = "This is a string!";
print_r((array) $test);

Output:

Array
(
    [0] => This is a string!
)

That said I find the code strange, I don't see the need for the loop, it could just be:

$key = "upload_8_fid_aids.tmp";

public function to_key($key) {
    $s = $this->table; //$s = kv
    $s .= '-' . $this->primarykey[0] . '-' . $key;
    return $s;
}

Upvotes: 2

DonOfDen
DonOfDen

Reputation: 4108

Converting an object to an array:

 <?php
        /*** create an object ***/
        $obj = new stdClass;
        $obj->foo = 'foo';
        $obj->bar = 'bar';
        $obj->baz = 'baz';

        /*** cast the object ***/
        $array = (array) $obj;

        /*** show the results ***/
        print_r( $array );
    ?>

Result:

Array
(
    [foo] => foo
    [bar] => bar
    [baz] => baz
)

Upvotes: 0

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324820

Any type enclosed in parentheses is telling PHP to cast the following thing to that type.

In this case, it's a cheap way to avoid having to check if( is_array($key)), by just forcing it to be one.

Upvotes: 2

Related Questions