Code Newbie
News     Forums     Search     Members     Sign Up    

My Code Newbie
Username

Password

Articles/Snippets
ASP Classic
ASP.NET
C
C#
C++
HTML / CSS
Java
Javascript
Linux / BSD
Perl
PHP
Python
Ruby
SQL
VB 6
VB.NET

C.N. Friends
  Planet Rome

Link to Us!
Code Newbie
  Code Newbie
    php
  » Arrays for beginners
      by Mike Milano
 Page 2 of 5 
< Previous     Next >

(Login to remove green text ads)
Create an array
Create an array

If you learn like I do, then it will probably be best if I show you some code before I move on. Creating an array with PHP is pretty simple.

Here are a few examples of how to create an array with PHP. Read the comments for the explanation.
PHP Code:
// empty array
$fruit = array();

// create an array of fruit
$fruit = array('apple''orange''pear');

// add a pineapple to the fruit array
$fruit[] = 'pineapple';

// now there are 4 items in the fruit array 
That is nice, but when would I ever create a fruit array? I know it's not a very practical example so I'll attempt to go further. If you have never used a mysql database before, just bare with me.

This example shows how one might get all the products from a database and return an array.
PHP Code:
function getProducts(){
  
// initialize empty array
  
$products = array();

  
// query the database
  
$result mysql_query("select product_name from products");

  
// loop through results
  
while ($row mysql_fetch_assoc($result)) {
    
// append product array
    
$products[] = $row['product_name'];
  }

  return 
$products;

Now this is not a very thorough example because of course you would most likely be dealing with other data such as price, category, etc with real store data, but it is a little more real-world than the fruit sample.

Let's move on.




 
 Page 2 of 5 
< Previous     Next >

Rate This Article
1 2 3 4 5 6 7 8 9 10





Copyright © 2000-2008, Milano Interactive
Web Hosting provided by Portal 360 Web Hosting