This forum is now read-only. Please use our new forums at discuss.codecademy.com.

Functions, Part I Forum

View Course » View Exercise

1844 points
50847e5ea0c7110200008295_932393476
Submitted by
Lee Tratnyek
over 4 years ago

Save yourself time and money!

I suppose it will be hard for me to promise you the money part, but your typing fingers should be happy by what I'm about to say.

If for some reason you ever find yourself manually using array_push() to push multiple elements to an array, you do not need a new line for every element. The array_push() function allows you to push one or more elements to the end of an array. When I completed this exercise, I pushed all 5 items into my array with one line of code. See my example, it passes!

<?php
// Create an array and push 5 elements on to it, then 
// print the number of elements in your array to the screen
$music_today = array();
array_push($music_today, "Danger Mouse", "Jack White", "Norah Jones", "Landon Spradlin", "The Civil Wars");
print count($music_today);
?>

1 vote

permalink

@ Lee
That's exactly what I came to the forum to say! Ok, not exactly, but...

Bottom line is this: an array is an array, regardless of the programming language. So it stands to reason that multiple elements can be put (or pushed, in this case) in an array with one command.

Here's my code:

<?php
    $newAlbum = array();
    array_push($newAlbum, "Running Away", "Send It To You", "Every Little Beat", "Stone Out Of My Mind", "Ground Up");
    echo count($newAlbum) . " tracks for the new album, so far. They are<br><br>";
    for($i = 0; $i < count($newAlbum); $i++) {
        echo $newAlbum[$i] . "<br>";
    }
    ?>

777 points
5198aefe94cf37ba2900070c_9511443
Submitted by
Simon Latham
over 4 years ago


0 votes

permalink

For those more knowledgeable in PHP, I do have a related question. Is it better practice to use $array[ ] = when adding one element, and array_push( ) when adding multiple elements?

I ask because of the note at http://php.net/manual/en/function.array-push.php which indicates:

Note: If you use array_push() to add one element to the array it's better to use $array[] = because in that way there is no overhead of calling a function.

This would lead me to believe that array_push() is better when adding multiple elements as only a single function call is performed, whereas you would want to avoid a function call all together if you are only pushing a single element.

1844 points
50847e5ea0c7110200008295_932393476
Submitted by
Lee Tratnyek
over 4 years ago

1 Comment

5198aefe94cf37ba2900070c_9511443 Simon Latham over 4 years ago

That's correct, Lee... hence the instruction for the exercise.