Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

array wrapped in parentheses in PHP (array)

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?

like image 626
McShaman Avatar asked Jan 05 '13 04:01

McShaman


People also ask

What does array [] mean in PHP?

Arrays ¶ An array in PHP is actually an ordered map. A map is a type that associates values to keys. This type is optimized for several different uses; it can be treated as an array, list (vector), hash table (an implementation of a map), dictionary, collection, stack, queue, and probably more.

What is a [] in PHP?

In many languages the [] notation stands for an array. Is the same as php's array_push() : it pushes an element in the variable that has [] at the end. If the variable is null, you can consider the square brackets like a declaration of an array.

What do square brackets mean in PHP?

In PHP, elements can be added to the end of an array by attaching square brackets ([]) at the end of the array's name, followed by typing the assignment operator (=), and then finally by typing the element to be added to the array.


2 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

like image 130
user1909426 Avatar answered Sep 20 '22 09:09

user1909426


(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

like image 21
PassKit Avatar answered Sep 20 '22 09:09

PassKit