0

So I have lots of arrays of the form:

$e = array( 
  "key1" => "value1",
  "key2" => "value2",
  "key3" => "value3",
  "key4" =? "value4"
);

And another array just declared as:

$a = array( );

What I want is to append $e to $a as an element, so

$a[0] = array( 
  "key1" => "value1",
  "key2" => "value2",
  "key3" => "value3",
  "key4" =? "value4"
);

So I can then go:

$count = count( $a );
for ( $j = 0; $j < $count; $j++ )
{
  echo $a[$j]["key1"];
}

and it will print "value1".

I will be repeating this process for all of the $e, so $a may not always be empty when the $e is appended - it may have had other $e appended previously. I thought that array_push would do this but it doesn't. Thanks for any help.

1 Answer 1

3

The quick and dirty way is pretty simple:

$a[] = $e;

and then do it again for any additional arrays. That will fill in the $a array starting with index zero and incrementing up.

If you wanted to use some sort of keys, you could do:

$a['firstarray'] = $e;

and accomplish much the same thing. The difference is that since keys must be unique, a screwup in that second method could overwrite an existing element. The first method has no chance of that happening.

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

3 Comments

Also using $a[] instead of array_push is a tad faster for items less than 100k
The $a[] method was the first thing I tried, before array_push, but that didn't work either. Anyway, I guess I'll work something out...
LOL, it was a typo in my code, the $a[] method did work after all. I guess typos are a lot harder to make when using 1-letter variable names like in the example I gave above ;)

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.