Chaya Cooper
Chaya Cooper

Reputation: 2530

Why would the first element in this array be empty?

I'm wondering why the first element in this array would be empty?

$first_names[] = array();
foreach ($rows as $row) { 
  $first_names[] = $row['first_name'];
}

The result of var_dump($first_names); is:

array(15) { [0]=> array(0) { } [1]=> string(5) "Johny" [2]=> string(5) "Jacob" ...} 

Upvotes: 1

Views: 511

Answers (4)

Surojit
Surojit

Reputation: 1292

It is empty because you are adding an array element to the 0th index in the $first_names variable.

You should try

$first_names = array();

Upvotes: 2

Tamil Selvan C
Tamil Selvan C

Reputation: 20209

Initialize array as

$first_names = array();

Upvotes: 2

user229044
user229044

Reputation: 239301

This line

$first_names[] = array();

is explicitly pushing an empty array onto the front of $first_names. That's what $array[]=... does; it's a synonym for array_push.

I think your intention was to initialize the variable to an empty array. For this you'd simply use the assignment operator:

$first_names = array();

Upvotes: 3

Jason
Jason

Reputation: 13766

$first_names[] = array();

should be

$first_names = array();

Upvotes: 6

Related Questions