1

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" ...} 
1
  • Technically, it's not empty; rather, it holds an empty array. Commented Apr 17, 2013 at 18:35

4 Answers 4

6

$first_names[] = array();

should be

$first_names = array();

Sign up to request clarification or add additional context in comments.

Comments

3

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();

1 Comment

You're absolutely right :-D Quick question - I noticed that I need to include it in the foreach loop when I create a subarray - why is that? $students[] = array($row['first_name'], $row['last_name']);
2

Initialize array as

$first_names = array();

Comments

2

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();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.