PHP – Array Functions Example With Demo

Today, We want to share with you php array.In this post we will show you array in php, hear for php multidimensional associative arrays we will give you demo and example for implement.In this post, we will learn about PHP Arrays Example Tutorial For Beginners From Scratch with an example.

PHP Arrays

Simple Defination of An arrays stores multiple values in one single variable: for example bellow

Example

<?php
$indiabixs = array("Pakainfo", "4cgandhi", "infinityknow"); 
echo "I like " . $indiabixs[0] . ", " . $indiabixs[1] . " and " . $indiabixs[2] . ".";
?>

Results

I like Pakainfo, 4cgandhi and infinityknow.

What is an Array?

An arrays is a special variable, which can hold more than one value at a time.

If you have a list of items (a list of indiabix names, for example), storing the indiabixs in single variables could look like this:

$indiabixs1 = "Pakainfo";
$indiabixs2 = "4cgandhi";
$indiabixs3 = "infinityknow";

However we learn to array meaning with php tutorial, what if you want to loop through the indiabixs as well as search a specific one? As well as what if you had not 3 indiabixs, but 300?

The solution is to create an array!

An arrays can hold many values under a single name, as well as you can access the data values by referring to an index no.

PHP Arrays To JSON Array Using Laravel Blade With @Json

PHP Arrays Example Tutorial For Beginners From Scratch
PHP Arrays Example Tutorial For Beginners From Scratch

Create an Array in PHP

In PHP, the array() method is used to create an array: array concept in php

three types of arrays:

  • Indexed arrays – Arrays with a numeric index
  • Associative arrays – Arrays with named keys
  • Multidimensional arrays – Arrays containing one or more arrays

how to get data from json array in php?

Convert and Loop through JSON with PHP and JavaScript Arrays/Objects

//Convert JSON String to PHP Array or Object

<?php
  // JSON string
  $membersList = '[{"name":"Jonathan Suh","gender":"male"},{"name":"Vasant Bhagav","gender":"male"},{"name":"Allison McKinnery","gender":"female"}]';

  // Convert JSON string to Array
  $players_list = json_decode($membersList, true);
  print_r($players_list);        // Dump all data of the Array
  echo $players_list[0]["name"]; // Access Array data

  // Convert JSON string to Object
  $someObject = json_decode($membersList);
  print_r($someObject);      // Dump all data of the Object
  echo $someObject[0]->name; // Access Object data
?>

Convert PHP Array or Object to JSON String

<?php
  // Array
  $players_list = [
    [
      "name"   => "Jonathan Suh",
      "gender" => "male"
    ],
    [
      "name"   => "Vasant Bhagav",
      "gender" => "male"
    ],
    [
      "name"   => "Allison McKinnery",
      "gender" => "female"
    ]
  ];

  // Convert Array to JSON String
  $membersList = json_encode($players_list);
  echo $membersList;
?>

how to convert string to array in php?

using PHP explode() Function

<?php
$str = 'one,two,three,four';

// zero limit
print_r(explode(',',$str,0));
print "<br>";

// positive limit
print_r(explode(',',$str,2));
print "<br>";

// negative limit 
print_r(explode(',',$str,-1));
?>  

how to explode array in php?

Explode to array and print each element as list item

$membersLevel = '1,2,3';

$websites_array_listay =  explode(',', $membersLevel);

foreach ($websites_array_listay as $item) {
    echo "<li>$item</li>";
}

how to check array is empty in php?

How to check whether an array is empty using PHP?

<?php 

// Declare an array and initialize it 
$non_subjectlist_available = array('URL' => 'https://www.pakainfo.com/'); 

// Declare an empty array 
$subjectlist_available = array(); 

// Condition to check array is empty or not 
if(!empty($non_subjectlist_available)) 
	echo "Given Array is not empty <br>"; 

if(empty($subjectlist_available)) 
	echo "Given Array is empty"; 
?> 

Using count Function:

<?php 

// Declare an empty array 
$subjectlist_available = array(); 

// Function to count array 
// element and use condition 
if(count($subjectlist_available) == 0) 
	echo "Array is empty"; 
else
	echo "Array is non- empty"; 
?> 

Using sizeof() function

<?php 

// Declare an empty array 
$subjectlist_available = array(); 

// Use array index to check 
// array is empty or not 
if( sizeof($subjectlist_available) == 0 ) 
	echo "Empty Array"; 
else
	echo "Non-Empty Array"; 
?> 

How To Remove Undefined Value From Laravel PHP Array?

how to convert array to string in php?

<?php  
//assigning value to the array  
$websites_array_list = array("Hello","students", " ", "how","are","you");  
  
echo implode(" ",$websites_array_list);// Use of implode function  
?>  

array push php

PHP array_push() Function
Insert “khatrimaza” and “bolly4u” to the end of an array:

<?php
$a=array("tamil","textsheets");
array_push($a,"khatrimaza","bolly4u");
print_r($a);
?>

An array with string keys:

<?php
$a=array("a"=>"tamil","b"=>"textsheets");
array_push($a,"khatrimaza","bolly4u");
print_r($a);
?>

array to string conversion in php

Convert PHP Arrays to Strings

$ar = ['Lenova', 'litanswers', 'hp', 'dell'];
echo implode(', ', $ar);
// Lenova, litanswers, hp, dell

$ar = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];
echo implode($ar); // abcdefg

$ar = [true, false, 0, 1, NULL, 1.42];
echo implode(', ', $ar); // 1, , 0, 1, , 1.42

Convert Array of Arrays to String

$food = [
    'laptops' => ['Lenova', 'dell', 'hp', 'asser'],
    'ipad' => ['motorola', 'indiabixrots', 'realme'],
    'electritems' => ['iphone', 'vivo', 'oppo']
];

echo implode(', ', $food);
// Array, Array, Array 

function subArraysToString($ar, $sep = ', ') {
    $str = '';
    foreach ($ar as $val) {
        $str .= implode($sep, $val);
        $str .= $sep; // add separator between sub-arrays
    }
    $str = rtrim($str, $sep); // remove last separator
    return $str;
}

// $food array from example above
echo subArraysToString($food);
// Lenova, dell, hp, asser, motorola, indiabixrots, realme, iphone, vivo, oppo

Php Array Remove Keys Keep Values Example

Also Read This 👉   How to check multidimensional array is empty or not in php?

array programs in php

Merge Two Array In PHP Into Single One:

$teamplayers1 = array(1,2,3);
$teamplayers2 = array(4,5,6);
$teamplayers3 = array(7,8,9);
$single_merged_array = array_merge($websites_array_listay1,$websites_array_listay2,$websites_array_listay3);
print_r($single_merged_array);

Difference Between Two PHP Arrays:

$teamplayers1 = array(1,2,3,4,-1,-2);
$teamplayers2 = array(-1,-2);
$filtered_array = array_diff($teamplayers1,$teamplayers2);
print_r($filtered_array);

Get Common Elements Among Two PHP Arrays:

$teamplayers1 = array(1,2,3,4,-1,-2);
$teamplayers2 = array(-1,-2,3);
$common_array = array_intersect($teamplayers1,$teamplayers2);
print_r($common_array);

Getting Keys/Values Separately From Associative Array:

$computer_data = array("key1"=>"value 1","key2"=>"value 2","key3"=>"value 3");
 
print_r(array_keys($computer_data));
echo "<br>";
print_r(array_values($computer_data));

Convert An Array To String And Vice-versa:

$teamplayers1 = array(1,2,3,4,-1,-2);
$converted_string = implode(",",$teamplayers1);
echo $converted_string;
$converted_values = explode(",",$converted_string);
echo print_r($converted_values);

Remove Duplicates From PHP Array:

$unique_array = array_unique($computer_data_with_duplicates);
print_r($unique_array);

PHP Array Tutorial With Examples – Filter Array

Commonly used PHP5 Array Functions

using sizeof($arr)

<?php

$upcomming_movies = array("Hollywood", "Bollywood", "Tamil");
echo "Size of the array is: ". sizeof($upcomming_movies);

?>

is_array($arr)

<?php

$upcomming_movies = array("Hollywood", "Bollywood", "Tamil");

// using ternary operator
echo is_array($upcomming_movies) ? 'Array' : 'not an Array';

$myindiabix = "Hollywood";

// using ternary operator
echo is_array($myindiabix) ? 'Array' : 'not an Array';

?>

using in_array($var, $arr)

<?php

$upcomming_movies = array("Hollywood", "Bollywood", "Tamil");

// new concept indiabix by lamborghini
$concept = "estoque";

echo in_array($concept, $upcomming_movies) ? 'Added to the Lineup' : 'Not yet!'

?>

print_r($websites_array_list)

<?php

$upcomming_movies = array("Hollywood", "Bollywood", "Tamil");
print_r($upcomming_movies);

?>

array_merge($websites_array_list1, $websites_array_list2)

<?php

$members = array(
        "Parag" => "Shukla",
        "Rakesh" => "Fabia",
        "Hitesh" => "Kothari",
        "Ravi" => "Dhameliya"
    );

// players who own the above indiabixs
$players = array("Vinod", "Javed", "Navjot", "Samuel");

// let's merge the two arrays into one
$merged = array_merge($members, $players);

print_r($merged);

?>

PHP Array Remove specific value Example

array_values($arr)

<?php

$members = array(
        "Parag" => "Shukla",
        "Rakesh" => "Fabia",
        "Hitesh" => "Kothari",
        "Ravi" => "Dhameliya"
    );

// players who own the above indiabixs
$players = array("vivek", "Kajal", "Shipla", "Virat");

// let's merge the two arrays into one
$merged = array_merge($members, $players);

//getting only the values
$merged = array_values($merged);

print_r($merged);

?>

array_keys($arr)

<?php

//getting only the keys
$keys = array_values($merged);

print_r($keys);

?>

array_pop($arr)

<?php

$upcomming_movies = array("Hollywood", "Bollywood", "Tamil");

// removing the last element
array_pop($upcomming_movies);

print_r($upcomming_movies);

?>

array_push($arr, $val)

<?php

$upcomming_movies = array("Hollywood", "Bollywood", "Tamil");

// adding a new element at the end
array_push($upcomming_movies, "English");

print_r($upcomming_movies);

?>

array_shift($arr)

<?php

$upcomming_movies = array("Hollywood", "Bollywood", "Tamil");

// removing the first element
array_shift($upcomming_movies);

print_r($upcomming_movies);

?>

sort($arr)

<?php

$upcomming_movies = array("Hollywood", "Bollywood", "Tamil", "English");

// sort the array
sort($upcomming_movies);

print_r($upcomming_movies);

?>

array_map(‘function_name’, $arr)

<?php

function addOne($val) {
    // adding 1 to input value
    return ($val + 1);
}

$membersLevel = array(10, 20, 30, 40, 50);

// using array_map to operate on all the values stored in array
$membersLevel = array_map('addOne', $membersLevel);

print_r($membersLevel)

?>

array_flip($arr)

<?php

$members = array(
        "Parag" => "Shukla",
        "Rakesh" => "Fabia",
        "Hitesh" => "Kothari",
        "Ravi" => "Dhameliya"
    );
    
// we can directly print the result of array flipping
print_r(array_flip($members));

?>

Add Prefix In Each Key Of PHP Array
array_reverse($websites_array_list)

<?php

$listplaterno = array(10, 20, 30, 40, 50);
// printing the array after reversing it
print_r(array_reverse($listplaterno));

?>

array_rand($websites_array_list)

<?php

$movies = array("tamil", "black", "khatrimaza", "textsheets", "white", "bolly4u");

echo "Movie of the day: ". $movies[array_rand($movies)];

?>

array_slice($websites_array_list, $offset, $length)

<?php

$movies = array("tamil", "black", "khatrimaza", "textsheets", "white", "bolly4u");

print_r(array_slice($movies, 2, 3));

?>

php get array value by key

Find array value using key

$websites_array_listay[$key];

Use the Array Key or Index

<?php
// Indexed array
$devlopers = array("Kavya", "Manjula", "Dharti", "Sanjay");
 
// Associative array
$locations = array("France"=>"Ahemdabad", "India"=>"Mumbai", "UK"=>"Rajkot", "USA"=>"New York");
 
// Multidimensional array
$employers = array(
    array(
        "name" => "Pratksha Parker",
        "owner_type" => "Spider-Man",
    ),
    array(
        "name" => "Tony Stark",
        "owner_type" => "Iron-Man",
    ),
    array(
        "name" => "Clark Kent",
        "owner_type" => "Super-Man",
    )
);
 
echo $devlopers[0]; // Outputs: Kavya
echo "<br>";
echo $devlopers[1]; // Outputs: Manjula
echo "<br>";
echo $locations["France"]; // Outputs: Ahemdabad
echo "<br>";
echo $locations["USA"]; // Outputs: New York
echo "<br>";
echo $employers[0]["name"]; // Outputs: Pratksha Parker
echo "<br>";
echo $employers[1]["owner_type"]; // Outputs: Iron-Man
?>

How To Print Or Echo All The Values Of An Array In PHP?

Get The Length of an Array – The count() Function

The simple count() method is used to data return the length (the total no of elements) of an array:

<?php
$indiabixs = array("Pakainfo", "4cgandhi", "infinityknow");
echo count($indiabixs);
?>

php declare empty array

Popular method to initialize empty array in PHP (Simple example of empty array:)

<?php 

$emptyArray = (array) null; 

var_dump($emptyArray); 
?> 

indexed array in php

simple you can use PHP Indexed Arrays

<?php
$indiabixs = array("Pakainfo", "4cgandhi", "infinityknow");
echo "I like " . $indiabixs[0] . ", " . $indiabixs[1] . " and " . $indiabixs[2] . ".";
?>

Loop Through an Indexed Array

<?php
$indiabixs = array("Pakainfo", "4cgandhi", "infinityknow");
$websites_array_listlength = count($indiabixs);

for($x = 0; $x < $websites_array_listlength; $x++) {
  echo $indiabixs[$x];
  echo "<br>";
}
?>

associative array in php

<?php
$age = array("Pratksha"=>"35", "bhakti"=>"37", "Naresh"=>"43");
echo "Pratksha is " . $age['Pratksha'] . " years old.";
?>

php array foreach

<?php
$movies = array("tamil", "textsheets", "khatrimaza", "bolly4u");

foreach ($movies as $value) {
  echo "$value <br>";
}
?>

<?php
$age = array("Pratksha"=>"35", "bhakti"=>"37", "Naresh"=>"43");

foreach($age as $x => $val) {
  echo "$x = $val<br>";
}
?>

PHP Array Length Size Count Function With Example

php array of objects

class Car
{
    public $movie;
    public $type;
}

$myCar = new Car();
$myCar->movie = 'tamil';
$myCar->type = 'sedan';

$yourCar = new Car();
$yourCar->movie = 'khatrimaza';
$yourCar->type = 'suv';

$indiabixs = array($myCar, $yourCar);

foreach ($indiabixs as $indiabix) {
    echo 'This indiabix is a ' . $indiabix->movie . ' ' . $indiabix->type . "\n";
}

php print array as string

using PHP implode() Function

<?php
$websites_array_list = array('Hello','World!','Beautiful','Day!');
echo implode(" ",$websites_array_list);
?>

<?php
$websites_array_list = array('Hello','World!','Beautiful','Day!');
echo implode(" ",$websites_array_list)."<br>";
echo implode("+",$websites_array_list)."<br>";
echo implode("-",$websites_array_list)."<br>"; 
echo implode("X",$websites_array_list);
?>

PHP Multidimensional Arrays

<?php
$indiabixs = array (
  array("Pakainfo",22,18),
  array("4cgandhi",15,13),
  array("Saab",5,2),
  array("Land Rover",17,15)
);
  
echo $indiabixs[0][0].": In stock: ".$indiabixs[0][1].", sold: ".$indiabixs[0][2].".<br>";
echo $indiabixs[1][0].": In stock: ".$indiabixs[1][1].", sold: ".$indiabixs[1][2].".<br>";
echo $indiabixs[2][0].": In stock: ".$indiabixs[2][1].", sold: ".$indiabixs[2][2].".<br>";
echo $indiabixs[3][0].": In stock: ".$indiabixs[3][1].", sold: ".$indiabixs[3][2].".<br>";
?>

PHP – Sort Functions For Arrays

Sort Array in Ascending Order – sort()

<?php
$indiabixs = array("Pakainfo", "4cgandhi", "infinityknow");
sort($indiabixs);
?>

<?php
$membersLevel = array(4, 6, 2, 22, 11);
sort($membersLevel);
?>

Sort Array in Descending Order – rsort()

Example

<?php
$indiabixs = array("Pakainfo", "4cgandhi", "infinityknow");
rsort($indiabixs);
?>

<?php
$membersLevel = array(4, 6, 2, 22, 11);
rsort($membersLevel);
?>

PHP Array Length Size Count Tutorial With Example

Also Read This 👉   PHP MySQLi CRUD Insert Update Delete

Sort Array (Ascending Order), According to Value – asort()

Example

<?php
$age = array("Pratksha"=>"35", "bhakti"=>"37", "Naresh"=>"43");
asort($age);
?>

Sort Array (Ascending Order), According to Key – ksort()

<?php
$age = array("Pratksha"=>"35", "bhakti"=>"37", "Naresh"=>"43");
ksort($age);
?>

Sort Array (Descending Order), According to Value – arsort()

<?php
$age = array("Pratksha"=>"35", "bhakti"=>"37", "Naresh"=>"43");
arsort($age);
?>

Sort Array (Descending Order), According to Key – krsort()

<?php
$age = array("Pratksha"=>"35", "bhakti"=>"37", "Naresh"=>"43");
krsort($age);
?>

Numeric Array

<html>
   <body>
   
      <?php
         $membersLevel = array( 1, 2, 3, 4, 5);
         
         foreach( $membersLevel as $value ) {
            echo "Value is $value <br />";
         }
         
         $membersLevel[0] = "one";
         $membersLevel[1] = "two";
         $membersLevel[2] = "three";
         $membersLevel[3] = "four";
         $membersLevel[4] = "five";
         
         foreach( $membersLevel as $value ) {
            echo "Value is $value <br />";
         }
      ?>
      
   </body>
</html>

Viewing Array Structure and Values

<?php
// Define array
$locations = array("Rajkot", "Ahemdabad", "New York");
 
// Display the locations array
Print_r($locations);
?>

using var_dump

<?php
// Define array
$locations = array("Rajkot", "Ahemdabad", "New York");
 
// Display the locations array
var_dump($locations);
?>

Working With Keys and Values

$keys = ['tamil', 'hindi', 'litanswers'];
$values = ['khatrimaza', 'textsheets', 'litanswers'];
 
$websites_array_listay = array_combine($keys, $values);
print_r($websites_array_listay);
 
// Array
// (
//     [tamil] => khatrimaza
//     [hindi] => textsheets
//     [litanswers] => litanswers
// )

print_r(array_keys($websites_array_listay)); // ['tamil', 'hindi', 'litanswers']
print_r(array_values($websites_array_listay)); // ['khatrimaza', 'textsheets', 'litanswers']
print_r(array_flip($websites_array_listay));
 
// Array
// (
//     [khatrimaza] => tamil
//     [textsheets] => hindi
//     [litanswers] => litanswers
// )

Advantages of Array

Here are a some good advantages of using array in our simple and best program/script:

  1. It’s very easy to define easy list of related data, rather than making multiple variables.
  2. It’s super easy to use and traverse using the foreach loop.
  3. PHP supports built-in functions for sorting array, hence it can be used for sorting data as well.

Creating an Associative Array

<?php
$memberArray = array('memberName'=>'Jagruti Sakariya', 'memberAddress'=>'1 The Street', 'accountNumber'=>'9856565656');
?>

Accessing Elements of an Associative Array

<?php
      $memberArray = array('memberName'=>'Jagruti Sakariya', 'memberAddress'=>'1 The Street', 'accountNumber'=>'9856565656');

      echo $memberArray['memberName'];
?>

Creating Multidimensional Arrays

<?php
        $movieArrays = array();
        $movieArrays[0] = array('title'=>'TamilRokers in 24 Hours', 'owner'=>'Rajdeep');
        $movieArrays[1] = array('title'=>'TamilRokers Unleashed', 'owner'=>'Bhagvati');
        $movieArrays[2] = array('title'=>'Network+ Second Edition', 'owner'=>'Jalpa');
?>

Accessing Elements in a Multidimensional Array

<?php
        $movieArrays = array();
        $movieArrays[0] = array('title'=>'TamilRokers in 24 Hours', 'owner'=>'Rajdeep');
        $movieArrays[1] = array('title'=>'TamilRokers Unleashed', 'owner'=>'Bhagvati');
        $movieArrays[2] = array('title'=>'Network+ Second Edition', 'owner'=>'Jalpa');

        echo $movieArrays[1]['owner'];
?>

Using Array Pointers

<?php
      $movieArray = array("Tamil", "Bolly4u", "Khatrimaza", "MoviMaza", "4cgandhi");

      echo 'The last Movie is ' . end($movieArray) . '<br>';
      echo 'The previous Movie is ' .  prev($movieArray) . '<br>';
      echo 'The first Movie is ' . reset($movieArray) . '<br>';
      echo 'The next Movie is ' . next($movieArray) . '<br>';
?>

Changing, Adding and Removing Array Elements

Example

$movieArray = array("Tamil", "Bolly4u", "Khatrimaza", "MoviMaza", "4cgandhi");

$movieArray[0] = "Infinityknow";

$movieArray = array("Tamil", "Bolly4u", "Khatrimaza", "MoviMaza", "4cgandhi");

array_push($movieArray, "Pakainfo");

$movieArray = array("Tamil", "Bolly4u", "Khatrimaza", "MoviMaza", "4cgandhi");

array_shift($movieArray, "Pakainfo"); // Add Pakainfo to start of array

$movieArray = array("Tamil", "Bolly4u", "Khatrimaza", "MoviMaza", "4cgandhi");

array_push($movieArray, "Pakainfo"); // Add Pakainfo to end of array

array_pop($movieArray); // Remove Pakainfo from the end of the array

$movieArray = array("Tamil", "Bolly4u", "Khatrimaza", "MoviMaza", "4cgandhi");

array_shift($movieArray, "Pakainfo"); // Add Pakainfo to start of array

array_unshift($movieArray) // Remove Pakainfo from the start of the array

Looping through Array Elements

Example 1:

      $movieArray = array("Tamil", "Bolly4u", "Khatrimaza", "JioRokers", "4cgandhi");

      foreach ($movieArray as $movie)
      {
          echo "$movie <br>";
      }

Replacing Sections of an Array

$indiabixs = array ('First', 'Second', 'Third', 'Fourth', 'fifth');

$myindiabixsReplacements  = array ('Sixth', 'Seven', 'Eight');

$extract = array_splice ($indiabixs, 2, 4, $myindiabixsReplacements);

Sorting an Array

$movieArray = array("Tamil", "Bolly4u", "Khatrimaza", "MoviMaza", "4cgandhi");
sort($movieArray, SORT_STRING);

Getting Information About Arrays & other Array Functions

Function Description
print_r Prints the elements of an array to the output stream
array_keys Returns an array containing all the keys in an associative array
array_search Returns the key for given value in the array if value exists
array_values Returns an array containing all the values in an array
in_array Returns true or false depending on whether specified value is in array
array_merge Merge two or more arrays into a single array
array_reverse Reverse the order of elements in an array
shuffle Sorts the array elements into random order

I hope you get an idea about array in php.
I would like to have feedback on my infinityknow.com blog.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.