Posted inphp

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


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

name; // Access Object data
?>

Convert PHP Array or Object to JSON String

 "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

";

// positive limit
print_r(explode(',',$str,2));
print "
"; // 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 "
  • $item
  • "; }

    how to check array is empty in php?

    How to check whether an array is empty using PHP?

     '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 
    "; if(empty($subjectlist_available)) echo "Given Array is empty"; ?>

    Using count Function:

     
    
    

    Using sizeof() function

     
    
    

    How To Remove Undefined Value From Laravel PHP Array?

    how to convert array to string in php?

      
    

    array push php

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

    
    

    An array with string keys:

    "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

    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 "
    "; 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)

    
    

    is_array($arr)

    
    

    using in_array($var, $arr)

    
    

    print_r($websites_array_list)

    
    

    array_merge($websites_array_list1, $websites_array_list2)

     "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)

     "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)

    
    

    array_pop($arr)

    
    

    array_push($arr, $val)

    
    

    array_shift($arr)

    
    

    sort($arr)

    
    

    array_map(‘function_name’, $arr)

    
    

    array_flip($arr)

     "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)

    
    

    array_rand($websites_array_list)

    
    

    array_slice($websites_array_list, $offset, $length)

    
    

    php get array value by key

    Find array value using key

    $websites_array_listay[$key];
    

    Use the Array Key or Index

    "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 "
    "; echo $devlopers[1]; // Outputs: Manjula echo "
    "; echo $locations["France"]; // Outputs: Ahemdabad echo "
    "; echo $locations["USA"]; // Outputs: New York echo "
    "; echo $employers[0]["name"]; // Outputs: Pratksha Parker echo "
    "; 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 declare empty array

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

     
    

    indexed array in php

    simple you can use PHP Indexed Arrays

    
    

    Loop Through an Indexed Array

    ";
    }
    ?>
    

    associative array in php

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

    php array foreach

    ";
    }
    ?>
    
    "35", "bhakti"=>"37", "Naresh"=>"43");
    
    foreach($age as $x => $val) {
      echo "$x = $val
    "; } ?>

    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

    
    
    ";
    echo implode("+",$websites_array_list)."
    "; echo implode("-",$websites_array_list)."
    "; echo implode("X",$websites_array_list); ?>

    PHP Multidimensional Arrays

    ";
    echo $indiabixs[1][0].": In stock: ".$indiabixs[1][1].", sold: ".$indiabixs[1][2].".
    "; echo $indiabixs[2][0].": In stock: ".$indiabixs[2][1].", sold: ".$indiabixs[2][2].".
    "; echo $indiabixs[3][0].": In stock: ".$indiabixs[3][1].", sold: ".$indiabixs[3][2].".
    "; ?>

    PHP – Sort Functions For Arrays

    Sort Array in Ascending Order – sort()

    
    
    
    

    Sort Array in Descending Order – rsort()

    Example

    
    
    
    

    PHP Array Length Size Count Tutorial With Example

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

    Example

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

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

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

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

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

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

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

    Numeric Array

    
       
       
          ";
             }
             
             $membersLevel[0] = "one";
             $membersLevel[1] = "two";
             $membersLevel[2] = "three";
             $membersLevel[3] = "four";
             $membersLevel[4] = "five";
             
             foreach( $membersLevel as $value ) {
                echo "Value is $value 
    "; } ?>

    Viewing Array Structure and Values

    
    

    using var_dump

    
    

    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

    'Jagruti Sakariya', 'memberAddress'=>'1 The Street', 'accountNumber'=>'9856565656');
    ?>
    

    Accessing Elements of an Associative Array

    'Jagruti Sakariya', 'memberAddress'=>'1 The Street', 'accountNumber'=>'9856565656');
    
          echo $memberArray['memberName'];
    ?>
    

    Creating Multidimensional Arrays

    '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

    '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

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

    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 
    "; }

    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.

    I am Jaydeep Gondaliya , a software engineer, the founder and the person running Pakainfo. I'm a full-stack developer, entrepreneur and owner of Pakainfo.com. I live in India and I love to write tutorials and tips that can help to other artisan, a Passionate Blogger, who love to share the informative content on PHP, JavaScript, jQuery, Laravel, CodeIgniter, VueJS, AngularJS and Bootstrap from the early stage.

    Leave a Reply

    Your email address will not be published. Required fields are marked *

    We accept paid guest Posting on our Site : Guest Post Chat with Us On Skype