Search code examples
phparraysarray-push

Push new values to array while keeping old one intact


Not sure how to explain this or search for an answer in that matter.

I am creating a form to send and would like to use an existing array and push it to a new one without affecting the old one.

This is what I am doing right now:

$required_fields = array( "full_name", "email", "phone", "preferred_date" );
$whitelist = array_push( $required_fields, "patient_type", "appointment_time", "comments");

But it changes the $required fields array when doing it this way. How can I push those existing values into the $whitelist array without affecting the $required_fields?


Solution

  • http://php.net/manual/en/function.array-push.php

    If you take a look at the documentation of array_push it actually modifies the first parameter and only returns the number of new elements in the array.

    What you're trying to do is make a copy of the required_fields array and then add some new elements. You can use the array_merge function to get this done.

    http://www.php.net/manual/en/function.array-merge.php