TalkPHP

TalkPHP (http://www.talkphp.com/forums.php)
-   General (http://www.talkphp.com/general/)
-   -   (array) or array()? (http://www.talkphp.com/general/2031-array-array.html)

Orc 01-20-2008 05:46 PM

(array) or array()?
 
I really don't know how to sum this up but uhh, what's better or is it all the same? Such as:
PHP Code:

// Different method in making variables, arrays...
(array) $foo;
// Wouldn't $foo become an array just by that simply?
// Or this way:
 
$foo = array();
// I understand $foo gets assigned using the = operator doing that turns it into an array but wouldn't the other method just as good?

// Sorry if I am confusing you >.<

// Otherwise is (array) good for only Conditional Executing Statements like IF()? :S 









James

Alan @ CIT 01-20-2008 06:02 PM

They are both valid ways but you end up with slightly different results.

PHP Code:

<?php
(array) $foo;
$bar = array();

var_dump($foo);    // echo's "NULL"
var_dump($bar);    // echo's "array(0) ( )

So as you can see, typesetting the variable to an array using (array) doesn't actually create a new empty array where as array() will.

For the sake of standards, you should probably use array() when creating new arrays. Things like (array) (int) (long) etc are generally only used when converting a variable type to another:

PHP Code:

<?php

$foo 
16.123;
$bar = (int) $foo;

var_dump($bar);    // echo's int(16)

In this example, we have Long ($foo) which we then convert to an int by typecasting it using (int).

Alan.

Orc 01-20-2008 06:23 PM

Quote:

Originally Posted by Alan @ CIT (Post 9079)
They are both valid ways but you end up with slightly different results.

PHP Code:

<?php
(array) $foo;
$bar = array();

var_dump($foo);    // echo's "NULL"
var_dump($bar);    // echo's "array(0) ( )

So as you can see, typesetting the variable to an array using (array) doesn't actually create a new empty array where as array() will.

For the sake of standards, you should probably use array() when creating new arrays. Things like (array) (int) (long) etc are generally only used when converting a variable type to another:

PHP Code:

<?php

$foo 
16.123;
$bar = (int) $foo;

var_dump($bar);    // echo's int(16)

In this example, we have Long ($foo) which we then convert to an int by typecasting it using (int).

Alan.

Thanks! :D That gave me the exact answer I wanted! :]

ETbyrne 01-20-2008 07:00 PM

Great answer Alan!

xenon 01-20-2008 07:52 PM

Explicit type casting shouldn't be used to initalize variables, but to ensure you get the right data type when using it (that's what I believe, however).

PHP Code:

$a 3// implicit cast to integer
$a 'abcd'// implicit cast to string

(float) $a 'asdf'// why? not useful at all 



All times are GMT. The time now is 05:52 PM.

Powered by vBulletin® Version 3.6.8
Copyright ©2000 - 2013, Jelsoft Enterprises Ltd.
Search Engine Optimization by vBSEO 3.1.0