Home » Php » array wrapped in parentheses in PHP (array)

array wrapped in parentheses in PHP (array)

Posted by: admin July 12, 2020 Leave a comment


This is quite a simple question, but I am finding it hard to find an answer.

I have a script that has the following:

(array) $item->classes

I have seen array() but never (array). What does it do?

How to&Answers:

This is called typecasting. You can read more about on the PHP documentation. (array) is used to convert scalar or object to array see Converting to array


(array) will cast an object as an array

Assuming $item->classes->attribute_a = 1 and $item->classes->attribute_b = 2,

$object_to_array = (array)$item->classes; 

creates an associated array equivalent to array('attribute_a' => 1, 'attribute_b' => 2).

Typecasting is not just for arrays, it works between many different types. For example an integer could be cast as a string;

$i = 123;
$string_i = (string)$i;

Much more on typecasting here