<?php
/* ARRAY INITIALIZATION
* =============================================== */
$fruits = array();
$fruits = array( 'apples', 'avocados', 'oranges', 'bananas' );
$veggies = array( 'broccoli' => 1, 'lettuce' => 5, 'celery' => 0, 'spinach' => 5 );
$food = array( $fruits, $veggies );
$multi = array( array( 'foo' => 'bar' ), array( 'x' => 'y' ), 'key' => 'value', 3, 2, 1 );
list ( $first_item, $second_item ) = $fruits;
/* ARRAY CHECKS
* =============================================== */
$a = array();
is_array( $a ); // true
is_array( "string" ); // false
empty( $a ); // true
count( $a ); // 0
sizeof( $a ); // 0
/* ARRAY INDEX
* =============================================== */
$fruits[ 0 ]; // 'apples'
$veggies[ 'lettuce' ]; // 5
/* ADD
* =============================================== */
$fruits[] = 'apples'; // add to end
$veggies [ 'potato' ] = 3;
array_unshift( $fruits, "raspberries", "blueberries" ); // add to beginning
array_push( $fruits, "raspberries", "blueberries" ); // add to end
/* MERGE
* =============================================== */
$colors = array( 'green', 'red', 'yellow' );
$food = array( 'avocado', 'apple', 'banana' );
$colored_food = array_combine( $colors, $food ); // keys + values
$result = array_merge( $fruits, $veggies ); // 2nd array overrides 1st array, numbers are appended
$base = array( "orange", "banana", "apple", "raspberry" );
$replacements = array( 0 => "pineapple", 4 => "cherry" );
$replacements2 = array( 0 => "grape" );
$basket = array_replace( $base, $replacements, $replacements2 ); // keys are replaced or created
/* REMOVE
* =============================================== */
$fruit = array_shift( $fruits ); // remove item from begining
$fruit = array_pop( $fruits ); // remove item from end
unset( $fruits [ 'apples' ] );
$a = array( 1, 2, 3, NULL, "", "text", 4, 5 );
$a = array_filter( $a ); // removes empty and null values
$a = array_filter( $a, 'is_numeric' ); // returns only numeric values
/* FOR LOOP
* =============================================== */
// loop through each item
foreach ( $fruits as $fruit ) {
echo "fruit: $fruit \n";
}
// loop through each item with index
foreach ( $fruits as $inx => $fruit ) {
echo "$inx. fruit: $fruit \n";
}
$max = count( $fruits );
for ( $i = 0; $i < $max; $i ++ ) {
if ( $i === 0 ) {
continue;
} // advance loop
echo $fruits [ $i ];
if ( $i === 3 ) {
break;
} // stop loop
}
// convert to string
$fruits_str = implode( ',', $fruits );
// convert string to array
$fruits = explode( ',', $fruits_str );
Array notation, initializers, add / remove / merge and loop examples.
Be the first to comment
You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.