-->

Contoh Penggunaan Array pada PHP

Advertisement
Daftar Isi

    PHP Array

    array di php
    Array digunakan untuk menyimpan banyak nilai dalam satu variable php. Untuk membuat array php dapat menggunakan function array(), contoh mudah dalam membuat array

    $cars = array("Volvo", "BMW", "Toyota");
    echo count($cars);
    

    Dalam php terdapat 3 tipe array, diantaranya :
    • Indexed arrays = array dengan nomor index sebagai key
    • Associative arrays = array dengan key yang diberi nama sebagai pembeda dengan key lain.
    • Multidimensional arrays = array dengan array lain didalamnya biasa disebut sebagai array dalam array php.

    Indexed arrays

    Pada indexed arrays, key dari nilai pada arrays secara automatis selalu dimulai dengan key 0 (nol). Indexed arrays dapat dibuat dengan syntax
      
    $cars = array("Volvo", "BMW", "Toyota");
    

    atau
    $cars[0] = "Volvo";
    $cars[1] = "BMW";
    $cars[2] = "Toyota"; 
    

    Untuk memanggil nilai pada array dapat dilakukan dengan syntax
    echo $array[no.key]

    Associative arrays


    Associative array menggunakan nama key dibanding nomor key. Untuk membuat associative array tinggal menambahkan namakey didepan nilai sebuah array, contoh array dalam php

    $array = array(
        "foo" => "bar",
        "bar" => "foo",
    );
    
    // as of PHP 5.4
    $array = [
        "foo" => "bar",
        "bar" => "foo",
    ];
    

    atau

    $age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
    

    Untuk mengambil nilai array pada associative arrays dapat dilakukan dengan syntax
    echo $array[nama_key]

    Multidimensional Arrays

    Mulitidimensional Arrays atau Array Multidimensi Php adalah sebuah array yang didalamnya terdapat array lain sebagai key (array dalam array). Array multidimensi dapat dibuat dengan syntax
    $cars = array
      (
      array("Volvo",22,18),
      array("BMW",15,13),
      array("Saab",5,2),
      array("Land Rover",17,15)
      );
    

    Contoh array multidimensi php dapat dilihat pada contoh dibawah ini, misalkan kita memiliki tabel sebagai berikut :

    Name Stock Sold
    Volvo 22 18
    BMW 15 13
    Saab 5 2
    Land Rover 17 15

    Kita bisa menyimpan nilai pada tabel diatas dengan array multidimensi php sebagaii berikut

    $cars = array
      (
      array("Volvo",22,18),
      array("BMW",15,13),
      array("Saab",5,2),
      array("Land Rover",17,15)
      );
    

    Untuk menampilkan nilai array multidimensi diatas kita harus memilih baris dan kolom sebagai key pada pada array multidimensi diatas, contohnya

    echo $cars[0][0].": In stock: ".$cars[0][1].", sold: ".$cars[0][2].".
    "; // Volvo: In stock: 22, sold: 18
    echo $cars[1][0].": In stock: ".$cars[1][1].", sold: ".$cars[1][2].".
    "; // BMW: In stock: 15, sold: 13
    echo $cars[2][0].": In stock: ".$cars[2][1].", sold: ".$cars[2][2].".
    "; // Saab: In stock: 5, sold: 2.
    echo $cars[3][0].": In stock: ".$cars[3][1].", sold: ".$cars[3][2].".
    "; // Land Rover: In stock: 17, sold: 15.
    


    Berikut ini adalah tabel fungsi-fungsi array php yang bisa digunakan dalam memanipulasi array yang saya ambil dari PHP Array Functions - w3schools
     
    Function Description
    array() Creates an array
    array_change_key_case() Changes all keys in an array to lowercase or uppercase
    array_chunk() Splits an array into chunks of arrays
    array_column() Returns the values from a single column in the input array
    array_combine() Creates an array by using the elements from one "keys" array and one "values" array
    array_count_values() Counts all the values of an array
    array_diff() Compare arrays, and returns the differences (compare values only)
    array_diff_assoc() Compare arrays, and returns the differences (compare keys and values)
    array_diff_key() Compare arrays, and returns the differences (compare keys only)
    array_diff_uassoc() Compare arrays, and returns the differences (compare keys and values, using a user-defined key comparison function)
    array_diff_ukey() Compare arrays, and returns the differences (compare keys only, using a user-defined key comparison function)
    array_fill() Fills an array with values
    array_fill_keys() Fills an array with values, specifying keys
    array_filter() Filters the values of an array using a callback function
    array_flip() Flips/Exchanges all keys with their associated values in an array
    array_intersect() Compare arrays, and returns the matches (compare values only)
    array_intersect_assoc() Compare arrays and returns the matches (compare keys and values)
    array_intersect_key() Compare arrays, and returns the matches (compare keys only)
    array_intersect_uassoc() Compare arrays, and returns the matches (compare keys and values, using a user-defined key comparison function)
    array_intersect_ukey() Compare arrays, and returns the matches (compare keys only, using a user-defined key comparison function)
    array_key_exists() Checks if the specified key exists in the array
    array_keys() Returns all the keys of an array
    array_map() Sends each value of an array to a user-made function, which returns new values
    array_merge() Merges one or more arrays into one array
    array_merge_recursive() Merges one or more arrays into one array recursively
    array_multisort() Sorts multiple or multi-dimensional arrays
    array_pad() Inserts a specified number of items, with a specified value, to an array
    array_pop() Deletes the last element of an array
    array_product() Calculates the product of the values in an array
    array_push() Inserts one or more elements to the end of an array
    array_rand() Returns one or more random keys from an array
    array_reduce() Returns an array as a string, using a user-defined function
    array_replace() Replaces the values of the first array with the values from following arrays
    array_replace_recursive() Replaces the values of the first array with the values from following arrays recursively
    array_reverse() Returns an array in the reverse order
    array_search() Searches an array for a given value and returns the key
    array_shift() Removes the first element from an array, and returns the value of the removed element
    array_slice() Returns selected parts of an array
    array_splice() Removes and replaces specified elements of an array
    array_sum() Returns the sum of the values in an array
    array_udiff() Compare arrays, and returns the differences (compare values only, using a user-defined key comparison function)
    array_udiff_assoc() Compare arrays, and returns the differences (compare keys and values, using a built-in function to compare the keys and a user-defined function to compare the values)
    array_udiff_uassoc() Compare arrays, and returns the differences (compare keys and values, using two user-defined key comparison functions)
    array_uintersect() Compare arrays, and returns the matches (compare values only, using a user-defined key comparison function)
    array_uintersect_assoc() Compare arrays, and returns the matches (compare keys and values, using a built-in function to compare the keys and a user-defined function to compare the values)
    array_uintersect_uassoc() Compare arrays, and returns the matches (compare keys and values, using two user-defined key comparison functions)
    array_unique() Removes duplicate values from an array
    array_unshift() Adds one or more elements to the beginning of an array
    array_values() Returns all the values of an array
    array_walk() Applies a user function to every member of an array
    array_walk_recursive() Applies a user function recursively to every member of an array
    arsort() Sorts an associative array in descending order, according to the value
    asort() Sorts an associative array in ascending order, according to the value
    compact() Create array containing variables and their values
    count() Returns the number of elements in an array
    current() Returns the current element in an array
    each() Deprecated from PHP 7.2. Returns the current key and value pair from an array
    end() Sets the internal pointer of an array to its last element
    extract() Imports variables into the current symbol table from an array
    in_array() Checks if a specified value exists in an array
    key() Fetches a key from an array
    krsort() Sorts an associative array in descending order, according to the key
    ksort() Sorts an associative array in ascending order, according to the key
    list() Assigns variables as if they were an array
    natcasesort() Sorts an array using a case insensitive "natural order" algorithm
    natsort() Sorts an array using a "natural order" algorithm
    next() Advance the internal array pointer of an array
    pos() Alias of current()
    prev() Rewinds the internal array pointer
    range() Creates an array containing a range of elements
    reset() Sets the internal pointer of an array to its first element
    rsort() Sorts an indexed array in descending order
    shuffle() Shuffles an array
    sizeof() Alias of count()
    sort() Sorts an indexed array in ascending order
    uasort() Sorts an array by values using a user-defined comparison function
    uksort() Sorts an array by keys using a user-defined comparison function
    usort() Sorts an array using a user-defined comparison function

    Contoh program php menggunakan array


    // Array as (property-)map
    $map = array( 'version'    => 4,
                  'OS'         => 'Linux',
                  'lang'       => 'english',
                  'short_tags' => true
                );
                
    // strictly numerical keys
    $array = array( 7,
                    8,
                    0,
                    156,
                    -10
                  );
    // this is the same as array(0 => 7, 1 => 8, ...)
    
    $switching = array(         10, // key = 0
                        5    =>  6,
                        3    =>  7, 
                        'a'  =>  4,
                                11, // key = 6 (maximum of integer-indices was 5)
                        '8'  =>  2, // key = 8 (integer!)
                        '02' => 77, // key = '02'
                        0    => 12  // the value 10 will be overwritten by 12
                      );
                      
    // empty array;
    $empty = array();      
    

    $colors = array('red', 'blue', 'green', 'yellow');
    
    foreach ($colors as $color) {
        echo "Do you like $color?\n";
    }
    

    // This:
    $a = array( 'color' => 'red',
                'taste' => 'sweet',
                'shape' => 'round',
                'name'  => 'apple',
                4        // key will be 0
              );
    
    $b = array('a', 'b', 'c');
    
    // . . .is completely equivalent with this:
    $a = array();
    $a['color'] = 'red';
    $a['taste'] = 'sweet';
    $a['shape'] = 'round';
    $a['name']  = 'apple';
    $a[]        = 4;        // key will be 0
    
    $b = array();
    $b[] = 'a';
    $b[] = 'b';
    $b[] = 'c';
    
    // After the above code is executed, $a will be the array
    // array('color' => 'red', 'taste' => 'sweet', 'shape' => 'round', 
    // 'name' => 'apple', 0 => 4), and $b will be the array 
    // array(0 => 'a', 1 => 'b', 2 => 'c'), or simply array('a', 'b', 'c').
    
    Sumber :
    1. https://www.w3schools.com/php/php_arrays.asp
    2. https://www.php.net/manual/en/language.types.array.php
    Advertisement

    Disclaimer: Gambar, artikel ataupun video yang ada di web ini terkadang berasal dari berbagai sumber media lain. Hak Cipta sepenuhnya dipegang oleh sumber tersebut. Jika ada masalah terkait hal ini, Anda dapat menghubungi kami disini.
    Tambah Pengetahuan
    Disqus Comments