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?
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With