Question

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?

Was it helpful?

Solution 2

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

OTHER TIPS

I think you may want array_merge:

$whitelist = array_merge( $required_fields, array(
  "patient_type", 
  "appointment_time", 
  "comments"
));

This will leave $required_fields alone and $whitelist will be:

array(
  "full_name", 
  "email", 
  "phone", 
  "preferred_date", 
  "patient_type", 
  "appointment_time", 
  "comments"
);

You may want to use array_merge. Please, note that array_merge only accepts parameters of type array.

Instead, when you use array_push the first parameter will itself get modified. If you look at the documentation for array_push, the first parameter is passed by reference, and gets modified itself, which is why in your case $required_fields is being modified.

Correct code, therefore, should be:

$required_fields = array( "full_name", "email", "phone", "preferred_date" );
$whitelist = array_merge( $required_fields, array("patient_type", "appointment_time",  "comments"));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top