PHP Arrays

<?php /* ARRAY INITIALIZATION * =============================================== */ $fruits = array(); $fruits = array( 'apples', 'avocados', 'oranges', 'bananas' ); $veggies = array( 'broccoli' => 1, 'lettuce' => 5, 'celery' => 0, 'spinach' => 5 ); list ( $first_item, $second_item ) = $fruits; /* ARRAY INDEX * =============================================== */ $fruits[ 0 ]; // 'apples' $veggies[ 'lettuce' ]; // 5 /* ADD * =============================================== */ $fruits[] = ''; $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' ] ); /* 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.