arrays

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
mabufo
Forum Commoner
Posts: 81
Joined: Thu Jul 10, 2003 11:11 pm
Location: Orland Park, IL
Contact:

arrays

Post by mabufo »

I found this random image script - that makes use of arrays.

Code: Select all

<?php
$quote = array(
1  => "<img src='image1.jpg'>",
2  => "<img src='image2.jpg'>",
3  => "<img src='image3.jpg'>",
4  => "<img src='image4.jpg'>",
5  => "<img src='image5.jpg'>",
);
srand ((double) microtime() * 1000000);
  $randnum = rand(1,5);
echo"$quote[$randnum]";
?>
php.net's explanation or arrays was very confusing - so I was wondering if someone could simplify it for me. From what I can tell - the above array is assigned the name $quote. I imagine that each number, 1-5 - holds a line of text. Great. What I want to know - is syntax. Could someone please explain to me the syntax of this, and other arrays in php?

(also, I know that the rand() function calls a random number - and srand() seeds it, but could someone explain the correct implementation of rand()/srand() in php for me as well?)
printf
Forum Contributor
Posts: 173
Joined: Wed Jan 12, 2005 5:24 pm

Post by printf »

For something as simple as this, I would just use shuffle();, it does all the seeding and randomizing that is just as good as doing it your self...

Code: Select all

<?

// php 4.2.0 ^

$arr = array ( 1, 2, 3, 4, 5 );

shuffle ( $arr );

echo $arra[0];

?>

pif
User avatar
Luke
The Ninja Space Mod
Posts: 6424
Joined: Fri Aug 05, 2005 1:53 pm
Location: Paradise, CA

Re: arrays

Post by Luke »

Well, since that array has numerical keys, you could have actually assigned it like this:

Code: Select all

$quote = array("<img src='image1.jpg'>", "<img src='image2.jpg'>", "<img src='image3.jpg'>", "<img src='image4.jpg'>", "<img src='image5.jpg'>",);
The style used in your example is generally used for associative arrays where the key is a string:

Code: Select all

$quote = array('image1' => "<img src='image1.jpg'>", 'image2' => "<img src='image2.jpg'>")
So the syntax for an array is

Code: Select all

$name = array(value1, value2, value3, value4);
PHP will also allow addition to an array without knowing the index, so I could add a value to the above array with this:

Code: Select all

$name[] = "Value";
Does all that make sense?
User avatar
RobertGonzalez
Site Administrator
Posts: 14293
Joined: Tue Sep 09, 2003 6:04 pm
Location: Fremont, CA, USA

Post by RobertGonzalez »

Associative arrays have a string index to associate the value of the index to. Numerical arrays have integer indeces. Array can be multidimensional (meaning that array values can be arrays themselves) which allows for some power when it comes to data use within an array.

You can create an array in several ways:
1) Declaring a var to be an array and giving it data at the same time:

Code: Select all

$thisArray = array('Val1', 'Val2', 'Val3', 'Val4');
2) Declaring a var to be an array, and adding values to it later:

Code: Select all

$thisArray = array();
$thisArray['index1'] = 'Val1';
$thisArray[] = 'Val2';
$thisArray[$somevar] = 'Val3';
3) Creating an array by way of a function:

Code: Select all

$thisArray = explode('|', $this_long_string_to_split);
Arrays are a loaded beast. Once you wrap your mind around them you will find yourself using them a lot. Sometime more so than is healthy. But they are a powerful development tool. I absolutely love them and have used them for things such as FAQ lists to content managers.
User avatar
mabufo
Forum Commoner
Posts: 81
Joined: Thu Jul 10, 2003 11:11 pm
Location: Orland Park, IL
Contact:

Post by mabufo »

That certainly clears a few things up fellas, thank you kindly.
User avatar
mabufo
Forum Commoner
Posts: 81
Joined: Thu Jul 10, 2003 11:11 pm
Location: Orland Park, IL
Contact:

Post by mabufo »

one more thing - could someone explain to me the use of this foreach loop that goes through this array...

the array:

Code: Select all

$prices['Tires'] = 100;
$prices['Oil'] = 10;
$prices['Spark Plugs'] = 4;
the loop:

Code: Select all

foreach ($prices as $key => $value)
   echo $key.'=>'.$value.'<br />';
I understand that the array will pretty much be this: $prices = array ('Tires', 'Oil', 'Spark Plugs'); Except that each item will have the above price attached to it. However - I don't understand how the foreach loop will grab not only the keys (tires, oil, spark plugs) - but also the values attached to them (100, 10, 4). I will also add that I understand how a foreach loop is supposed to work - in that it takes the first key and stores that in a variable which in this case is $key, executes a statement - and then stores the next key in the variable - but what is the significance of adding '=> $value' to the end of the loop? H ow does that display the Price attached to the items in the array? Maybe it's all the new terminology - but I think after writing out my question I am getting a little closer to understanding how this works.

Bear with me!

By using an associative array - the element I enter becomes the key... and therefore the variable I attach to it becomes it's value... correct? So the foreach loop would actually output the array element - and it's contents. Right?

(did I just figure that out by myself? 8O )

EDIT: For my sake of completeness I'll try to explain to myself how to use the each(); function to access the same values. You guys need to tell me if I'm on the right track.

Code: Select all

while( $element = each( $prices) )
{
     echo $element[ 'key' ];
     echo ' - ';
     echo $element[ 'value'];
     echo '<br />';
}
It is my understanding that the each() function will take the first key element in the array (which is tires) - and stores it into the variable $element, along with it's value. The block of code inside the while loop will then neatly output the element 'Tires' and it's value - which would be 100. The loop will then go through the rest of the array until the end is reached. Correct?

If I am correct, and I did actually figure this out for myself - what confused me was that I didn't realize that the array element holds a value - and that the array element is not the value itself. Damn you associative arrays, and your confusing - but useful features! 8)


DOUBLE EDIT: Using the list() function is next in my book - so I may be back!
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

Post by John Cartwright »

You pretty much got it spot on. Keep experimenting with arrays and you it will soon become second nature. It's seriously one of those eurika (spelling?) moments. :wink:
but what is the significance of adding '=> $value' to the end of the loop?
If you simply do

Code: Select all

$array = array(
   'key' => 'value',
   'key2' => 'value'
);

foreach ($array as $var) 
{
   echo $var .' ';
} 

//outputs value value2
Or if you have numerical keys

Code: Select all

//keys are automatically assigned numerically
$array = array(
   'value',
   'value'
);


foreach ($array as $var) 
{
   echo $var .' ';
} 

//outputs value value2
Then you wouldn't generally need to worry about the keys at all, so no need fetching them.

Basically, it will ignore the keys and simply fetch the value of the element. It's also worth mentioning to look at all the different array functions in the manual along with the user comments (which are often very usefull I might add).
User avatar
RobertGonzalez
Site Administrator
Posts: 14293
Joined: Tue Sep 09, 2003 6:04 pm
Location: Fremont, CA, USA

Post by RobertGonzalez »

mabufo wrote:one more thing - could someone explain to me the use of this foreach loop that goes through this array...

the array:

Code: Select all

$prices['Tires'] = 100;
$prices['Oil'] = 10;
$prices['Spark Plugs'] = 4;
the loop:

Code: Select all

foreach ($prices as $key => $value)
   echo $key.'=>'.$value.'<br />';
I understand that the array will pretty much be this: $prices = array ('Tires', 'Oil', 'Spark Plugs'); Except that each item will have the above price attached to it. However - I don't understand how the foreach loop will grab not only the keys (tires, oil, spark plugs) - but also the values attached to them (100, 10, 4). I will also add that I understand how a foreach loop is supposed to work - in that it takes the first key and stores that in a variable which in this case is $key, executes a statement - and then stores the next key in the variable - but what is the significance of adding '=> $value' to the end of the loop? H ow does that display the Price attached to the items in the array? Maybe it's all the new terminology - but I think after writing out my question I am getting a little closer to understanding how this works.
You are almost right on. The prices array will look like this:

Code: Select all

$prices = array('Tires' => 100, 'Oil' => 10, 'Spark_Plugs' => 4);
Notice that I added the underscore in the Spark_Plugs index? That is because spaces are not allowed in index names. Your basic array setup is like this:

Code: Select all

$array = array($key => $value);
So when you foreach the array, in the fashion you posted, you are saying you want to see the array broken down into keys and values.
Robert Plank
Forum Contributor
Posts: 110
Joined: Sun Dec 26, 2004 9:04 pm
Contact:

Post by Robert Plank »

Better way to do it:

Code: Select all

<?php
$quote = array(
   'image1.jpg', 'image2.jpg', 'image3.jpg', 'image4.jpg', 'image5.jpg'
);

echo "<img src='" . $quote[array_rand($quote)] . "'>";

?>
That way you don't even have to worry about the keys, or rand() or anything.

By the way you don't need to seed the random number generator in PHP anymore when using rand().
Post Reply