Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Questions on Array
  • Practice Array
  • MCQs on Array
  • Tutorial on Array
  • Types of Arrays
  • Array Operations
  • Subarrays, Subsequences, Subsets
  • Reverse Array
  • Static Vs Arrays
  • Array Vs Linked List
  • Array | Range Queries
  • Advantages & Disadvantages
Open In App
Next Article:
How to check an element is exists in array or not in PHP ?
Next article icon

How to Insert a New Element in an Array in PHP ?

Last Updated : 15 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In PHP, an array is a type of data structure that allows us to store similar types of data under a single variable. The array is helpful to create a list of elements of similar types, which can be accessed using their index or key.

We can insert an element or item in an array using the below functions:

Table of Content

  • Using array_unshift() Function
  • Using array_push() Function
  • Using array_merge() Function
  • Using array_splice() Function
  • Using Assignment to Index

Using array_unshift() Function

The array_unshift() Function is used to add one or more than one element at the beginning of the array. and these elements get inserted at the beginning of the array. because of the inserted elements or items in the array, the length of the array also gets increased by the number of elements inserted or added in the array. After inserting the elements, we can use the print_r() function to print the array information.

Below are examples of how to do it: Let’s see how to insert an element at the beginning of the array using the array_unshift() function.

Input:  names[] = array("portal", "for", "geeks"),
size = 3, capacity = 3

Output: names[] = array("_", "_", "portal", "for", "geeks"),
size = 5, capacity = 5

Example 1: In this example, we use an indexed array to insert elements at the beginning of the array using the array_unshift() function.

PHP
<?php $names = array("portal", "for", "geeks"); array_unshift($names, "A", "Computer science"); print_r($names); ?> 

Output
Array (     [0] => A     [1] => Computer science     [2] => portal     [3] => for     [4] => geeks )  

Example 2: In this example, we use an associative array to insert elements at the beginning of the array using the array_unshift() function

PHP
<?php  // Declare an associative array $array = array(       "language1" => "CSS",        "language2" => "PHP",        "language3" => "MySQL" );  array_unshift($array, "HTML"); print_r($array);  ?> 

Output
Array (     [0] => HTML     [language1] => CSS     [language2] => PHP     [language3] => MySQL )  

Using array_push() Function

The array_push() Function function is used to push new elements into an array. We can push one or more than one element into the array and these elements get inserted to the end of the array and because of the pushed elements into the array, the length of the array also gets incremented by the number of elements pushed into the array. After inserting the elements, we use the print_r() function to print the array information.

Below are examples of how to do it: Let’s see how to insert an element at the end of the array using the array_push() function.

Input:  arr[] = array("Example", "based", "on"), 
size = 5, capacity = 5

Output: arr[] = array("Example", "based", "on", "_", "_"),
size = 5, capacity = 5

Example 3: In this example, we use an indexed array to insert elements at the end of the array using the array_push() function.

PHP
<?php $array_name = array("Example", "based", "on"); array_push($array_name, "PHP", "language"); print_r($array_name); ?> 

Output
Array (     [0] => Example     [1] => based     [2] => on     [3] => PHP     [4] => language )  

Example 4: If we want to add a single element at the end of an array.

PHP
<?php  $array = array("Technical", "Content", "Writer"); $array[] = "at GFG"; print_r($array);  ?> 

Output
Array (     [0] => Technical     [1] => Content     [2] => Writer     [3] => at GFG )  

Using array_merge() Function

The array_merge() Function is used to merge two or more arrays into a single array. This function is used to merge the elements or values of two or more arrays together into a single array. The merging occurs in such a manner that the values of one array are appended at the end of the previous array.

Example 5: The array_merge() function merges elements of one or more than one array into one array.

PHP
<?php $array1 = array("GFG", "stands", "for"); $array2 = array("Geeks", "for", "Geeks"); $merge = array_merge($array1, $array2); print_r($merge); ?> 

Output
Array (     [0] => GFG     [1] => stands     [2] => for     [3] => Geeks     [4] => for     [5] => Geeks )  

Using array_splice() Function

It is an advanced and extended version of the array_slice() function, where we not only remove elements from an array but can also add other elements to the array. The function generally replaces the existing element with elements from other arrays and returns an array of removed or replaced elements.

Example 6: The array_splice() method will remove elements and add other elements according to the position parameters.

PHP
<?php  // PHP program to illustrate the use // of array_splice() function  $array1 = [     "1" => "Geeks",     "2" => "for",     "3" => "geeks",     "4" => "is",     "5" => "fun", ];  $array2 = ["6" => "are", "7" => "great"];  echo "The returned array: \n"; print_r(array_splice($array1, 1, 4, $array2));  echo "\nThe original array is modified to: \n"; print_r($array1);  ?> 

Output
The returned array:  Array (     [0] => for     [1] => geeks     [2] => is     [3] => fun )  The original array is modified to:  Array (     [0] => Geeks     [1] => are     [2] => great )  

Using Assignment to Index

To insert a new element into an array in PHP, manually shift elements to create space at the desired index, then assign the new element to that index. This method maintains array integrity without using specialized functions.

Example:

PHP
<?php function insertElement(&$array, $index, $element) {     // Shift elements to make space at $index     for ($i = count($array); $i > $index; $i--) {         $array[$i] = $array[$i - 1];     }          // Insert the new element at $index     $array[$index] = $element; }  // Example usage $array = [1, 2, 3, 4, 5]; insertElement($array, 2, 'new element'); // Insert 'new element' at index 2  // Print the modified array print_r($array); ?> 

Output
Array (     [0] => 1     [1] => 2     [2] => new element     [3] => 3     [4] => 4     [5] => 5 ) 


Next Article
How to check an element is exists in array or not in PHP ?
author
garimamahawar2002
Improve
Article Tags :
  • Arrays
  • PHP
  • TrueGeek
  • Web Technologies
  • Arrays
  • php
  • PHP-array
  • PHP-function
  • PHP-Questions
  • TrueGeek-2021
  • Web technologies
Practice Tags :
  • Arrays
  • Arrays

Similar Reads

  • Insert Element at a Given Position in an Array
    Given an array of integers, the task is to insert an element at a given position in the array. Examples: Input: arr[] = [10, 20, 30, 40], pos = 2, ele = 50Output: [10, 50, 20, 30, 40] Input: arr[] = [], pos = 1, ele = 20Output: [20] Input: arr[] = [10, 20, 30, 40], pos = 5, ele = 50Output: [10, 20,
    7 min read
  • How to check an element is exists in array or not in PHP ?
    An array may contain elements belonging to different data types, integer, character, or logical type. The values can then be inspected in the array using various in-built methods : Approach 1 (Using in_array() method): The array() method can be used to declare an array. The in_array() method in PHP
    2 min read
  • How to find the index of an element in an array using PHP ?
    In this article, we will discuss how to find the index of an element in an array in PHP. Array indexing starts from 0 to n-1. Here we have some common approaches Table of Content Using array_search() FunctionUsing array_flip()Using a custom functionUsing a foreach LoopUsing array_keys FunctionUsing
    6 min read
  • How to get elements in reverse order of an array in PHP ?
    An array is a collection of elements stored together. Every element in an array belong to a similar data type. The elements in the array are recognized by their index values. The elements can be subjected to a variety of operations, including reversal. There are various ways to reverse the elements
    4 min read
  • How to Add an Element to an Array in Java?
    In Java, arrays are of fixed size, and we can not change the size of an array dynamically. We have given an array of size n, and our task is to add an element x into the array. In this article, we will discuss the New Different Ways to Add an Element to an ArrayThere are two different approaches we
    3 min read
  • How to delete an Element From an Array in PHP ?
    To delete an element from an array means to remove a specific value or item from the array, shifting subsequent elements to the left to fill the gap. This operation adjusts the array's length accordingly, eliminating the specified element. This article discusses some of the most common methods used
    4 min read
  • JavaScript - Insert Element in an array
    In JavaScript elements can be inserted at the beginning, end, and at any specific index. JS provides several methods to perform the operations. At the Beginning This operation inserts an element at the start of the array. The unshift() method is commonly used, which mutates the original array and re
    2 min read
  • Inserting Elements in an Array - Array Operations
    In this post, we will look into insertion operation in an Array, i.e., how to insert into an Array, such as: Insert Element at the Beginning of an ArrayInsert Element at a given position in an ArrayInsert Element at the End of an ArrayInsert Element at the Beginning of an ArrayInserting an element a
    2 min read
  • How to get total number of elements used in array in PHP ?
    In this article, we will discuss how to get total number of elements in PHP from an array. We can get total number of elements in an array by using count() and sizeof() functions. Using count() Function: The count() function is used to get the total number of elements in an array. Syntax: count(arra
    2 min read
  • Find the Most Frequent Element in an Array in PHP
    Given an array, i.e. $arr, the task is to find the most frequent element in an array. There are multiple ways to solve this problem in PHP we will be going to discuss them. These problems can be used during data analysis, Web Analytics, or highly used in fraud detection. Example: Input: $array = [1,
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences