Go Back   CodingForums.com > :: Server side development > PHP

Before you post, read our: Rules & Posting Guidelines

Reply
 
Thread Tools Rate Thread
Enjoy an ad free experience by logging in. Not a member yet? Register.
Old 01-15-2013, 12:49 PM   PM User | #1
zaltek
New Coder

 
Join Date: Dec 2010
Posts: 24
Thanks: 7
Thanked 0 Times in 0 Posts
zaltek is an unknown quantity at this point
Arrow Initializing Arrays

I have seen arrays in PHP initialized in the following ways:

$some_array1 = ...
$some_array2[] = ...

What's the difference between initializing arrays in these ways? Why do some require [] brackets and others don't?
zaltek is offline   Reply With Quote
Old 01-15-2013, 02:02 PM   PM User | #2
Fou-Lu
God Emperor


 
Fou-Lu's Avatar
 
Join Date: Sep 2002
Location: Saskatoon, Saskatchewan
Posts: 15,640
Thanks: 4
Thanked 2,448 Times in 2,417 Posts
Fou-Lu is a name known to allFou-Lu is a name known to allFou-Lu is a name known to allFou-Lu is a name known to allFou-Lu is a name known to allFou-Lu is a name known to all
Both are valid. Neither will throw an error in PHP assuming that $some_array2 isn't already in use as a scalar value.
PHP Code:
$a1 = array(); // valid
$a2 = []; // valid 5.4+
$a3[] = 'a val'// valid 
$a4 = array('a val'); // valid

$a5 = new stdclass;
$a5[] = 'val'// invalid.

$a6 'string';
$a6[] = 'string'// invalid 
Typically I use $a = array(); since its clear its an array.
Fou-Lu is offline   Reply With Quote
Old 01-16-2013, 11:52 AM   PM User | #3
zaltek
New Coder

 
Join Date: Dec 2010
Posts: 24
Thanks: 7
Thanked 0 Times in 0 Posts
zaltek is an unknown quantity at this point
PHP Code:
$a3[] = 'a val'// valid 
So this means if I want to define an array with both an index and a value, I need to use the brackets next to the variable's name, right?
zaltek is offline   Reply With Quote
Reply

Bookmarks

Tags
php array brackets

Jump To Top of Thread


Thread Tools
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off

Forum Jump


All times are GMT +1. The time now is 09:19 PM.


Advertisement
Log in to turn off these ads.