Php add array contents to array

Php add array contents to array

  • Different ways to write a PHP code
  • How to write comments in PHP ?
  • Introduction to Codeignitor (PHP)
  • How to echo HTML in PHP ?
  • Error handling in PHP
  • How to show All Errors in PHP ?
  • How to Start and Stop a Timer in PHP ?
  • How to create default function parameter in PHP?
  • How to check if mod_rewrite is enabled in PHP ?
  • Web Scraping in PHP Using Simple HTML DOM Parser
  • How to pass form variables from one page to other page in PHP ?
  • How to display logged in user information in PHP ?
  • How to find out where a function is defined using PHP ?
  • How to Get $_POST from multiple check-boxes ?
  • How to Secure hash and salt for PHP passwords ?
  • Program to Insert new item in array on any position in PHP
  • PHP append one array to another
  • How to delete an Element From an Array in PHP ?
  • How to print all the values of an array in PHP ?
  • How to perform Array Delete by Value Not Key in PHP ?
  • Removing Array Element and Re-Indexing in PHP
  • How to count all array elements in PHP ?
  • How to insert an item at the beginning of an array in PHP ?
  • PHP Check if two arrays contain same elements
  • Merge two arrays keeping original keys in PHP
  • PHP program to find the maximum and the minimum in array
  • How to check a key exists in an array in PHP ?
  • PHP | Second most frequent element in an array
  • Sort array of objects by object fields in PHP
  • PHP | Sort array of strings in natural and standard orders
  • How to pass PHP Variables by reference ?
  • How to format Phone Numbers in PHP ?
  • How to use php serialize() and unserialize() Function
  • Implementing callback in PHP
  • PHP | Merging two or more arrays using array_merge()
  • PHP program to print an arithmetic progression series using inbuilt functions
  • How to prevent SQL Injection in PHP ?
  • How to extract the user name from the email ID using PHP ?
  • How to count rows in MySQL table in PHP ?
  • How to parse a CSV File in PHP ?
  • How to generate simple random password from a given string using PHP ?
  • How to upload images in MySQL using PHP PDO ?
  • How to check foreach Loop Key Value in PHP ?
  • How to properly Format a Number With Leading Zeros in PHP ?
  • How to get a File Extension in PHP ?
  • How to get the current Date and Time in PHP ?
  • PHP program to change date format
  • How to convert DateTime to String using PHP ?
  • How to get Time Difference in Minutes in PHP ?
  • Return all dates between two dates in an array in PHP
  • Sort an array of dates in PHP
  • How to get the time of the last modification of the current page in PHP?
  • How to convert a Date into Timestamp using PHP ?
  • How to add 24 hours to a unix timestamp in php?
  • Sort a multidimensional array by date element in PHP
  • Convert timestamp to readable date/time in PHP
  • PHP | Number of week days between two dates
  • PHP | Converting string to Date and DateTime
  • How to get last day of a month from date in PHP ?
  • PHP | Change strings in an array to uppercase
  • How to convert first character of all the words uppercase using PHP ?
  • How to get the last character of a string in PHP ?
  • How to convert uppercase string to lowercase using PHP ?
  • How to extract Numbers From a String in PHP ?
  • How to replace String in PHP ?
  • How to Encrypt and Decrypt a PHP String ?
  • How to display string values within a table using PHP ?
  • How to write Multi-Line Strings in PHP ?
  • How to check if a String Contains a Substring in PHP ?
  • How to append a string in PHP ?
  • How to remove white spaces only beginning/end of a string using PHP ?
  • How to Remove Special Character from String in PHP ?
  • How to create a string by joining the array elements using PHP ?
  • How to prepend a string in PHP ?
Читайте также:  Html input selected color

Источник

Add Array to Array in PHP

Add Array to Array in PHP

  1. Using the for and foreach Loops to Add Array to Array in PHP
  2. Using the array_merge() Function to Add Array to Array in PHP
  3. Using the array_push() Function to Add Array to Array in PHP

Arrays contain a series of indexed elements of the same data type, often for faster iteration and data management.

Typically, to access array elements, you will loop over the array. For example, in a PHP application, an array could hold data from the registration form, and another array could hold data from the account details section. To use both arrays in one sequence, we need to add both arrays. To achieve this, we need to append the second array to the first, and different functions behave differently.

This tutorial discusses the different methods to add two arrays together to form one array in PHP.

Using the for and foreach Loops to Add Array to Array in PHP

A simple method to add an array to another array is to select the second array, loop through all the elements, and append each element to the first array. However, this particular solution is rather long and inefficient for larger arrays.

$container = ["hair extension", "scissors"]; $shopping_lists = ["hair cream", "hair fryer", "makeup set"]; for($index = 0; $index  count($shopping_lists ); $index++)  array_push($container, $shopping_lists[$index]); > print_r($container) 
Array (  [0] hair extension  [1] scissors  [2] hair cream  [3] hair fryer  [4] makeup set )  true 

Also, you can apply the same approach to an associative array. However, it comes with the same inefficiency and complexity.

$customer = array(  "name" => "Garner",  "email" => "g.abded@gmail.com",  "age" => 34,  "gender" => "female",  "account_type" => "starter" );  $account = array(  "current_course" => "Ruby Crash Course",  "payment_channel" => "Stripe",  "browser" => "Edge" );  foreach($account as $key => $value)   $customer[$key] = $value; >  print_r($customer) 
Array (  [name] Garner  [email] g.abded@gmail.com  [age] 34  [gender] female  [account_type] starter  [current_course] Ruby Crash Course  [payment_channel] Stripe  [browser] Edge )  true 

Using the array_merge() Function to Add Array to Array in PHP

The array_merge() function merges two or more arrays and appends the elements of one array to the end of the previous array, and so on, till the last array. This function works for index, associative and multidimensional arrays. Unlike the previous method, this approach creates a new array and does not append to the first array.

This method can work with multiple arrays. In more detail, we can use this approach to add the key-value pair (associative arrays) to one another to form one single array. The same goes for index arrays.

$details = [  "name" => "Clement",  "email" => "clement@gmail.com",  "gender" => "male" ];  $accounts = [  "card" => "mastercard",  "processor" => "stripe",  "pro" => True ];  $account_details = array_merge($details, $accounts);  print_r($account_details); 
Array (  [name] Clement  [email] clement@gmail.com  [gender] male  [card] mastercard  [processor] stripe  [pro] 1 )  true 

Here is how to use the array_merge() function on three arrays.

$details = [  "name" => "Clement",  "email" => "clement@gmail.com",  "gender" => "male" ]; $accounts = [  "card" => "mastercard",  "processor" => "stripe",  "pro" => True ]; $functions = [  "movies" => "inferno" ]; $account_details = array_merge($details, $accounts, $functions); print_r($account_details); 
Array (  [name] Clement  [email] clement@gmail.com  [gender] male  [card] mastercard  [processor] stripe  [pro] 1  [movies] inferno )  true 

This method is compatible with all PHP 7.0 versions and above.

Using the array_push() Function to Add Array to Array in PHP

The array_push() function pushes the array(s) onto the end of the array like a stack (LIFO). You can use this function to add an index array to an associative array, and it will automatically create a numerical index for the index array pushed to the associative array. If two index arrays are pushed, the first index array holds the numerical index of 0, and the second index array holds the numerical index of 1. For N arrays pushed, the numerical index will be N-1 .

Additionally, you can push index arrays to an index array and associative arrays to an associative array.

$basic_data = ['Location' => 'Mumbai', 'Tier' => 'Three']; $tools = ['Geology', 'Machine Learning']; $BD_Tools = array_push($basic_data, $tools);  print_r($basic_data); 
Array (  [Location] Mumbai  [Tier] Three  [0] Array  (  [0] Geology  [1] Machine Learning  ) )  true 

In addition, use the . operator within the array_push() function to allow all the elements within the pushed array(s) to have their own numerical index rather than one for all.

$basic_data = ['Location' => 'Mumbai', 'Tier' => 'Three']; $tools = ['Geology', 'Machine Learning']; $BD_Tools = array_push($basic_data, . $tools);  print_r($basic_data); 
Array (  [Location] Mumbai  [Tier] Three  [0] Geology  [1] Machine Learning )  true 

For associative array push operations, you can’t use the . operator, as it will throw an error.

TypeError: array_push() does not accept unknown named parameters null 

Therefore, the only way to use array_push() function with two or more arrays is via the default means.

$basic_data = ['Location' => 'Mumbai', 'Tier' => 'Three']; $tools = ['Course' => 'Geology', 'Approach' => 'Machine Learning']; $BD_Tools = array_push($basic_data, $tools);  print_r($basic_data); 
Array (  [Location] Mumbai  [Tier] Three  [0] Array  (  [Course] Geology  [Approach] Machine Learning  )  )  true 

Olorunfemi is a lover of technology and computers. In addition, I write technology and coding content for developers and hobbyists. When not working, I learn to design, among other things.

Источник

Оцените статью