0

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!

2
  • I think the $key is an object and they are converting it to an Array!! Commented Jul 25, 2013 at 6:06
  • 2
    @TomPHP $k is a string Commented Jul 25, 2013 at 6:09

3 Answers 3

2

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;
}
Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

0

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
)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.