Advertisement:

Author Topic: PHP Lesson 05 - arrays  (Read 89212 times)

Offline Parham

  • SMF Friend
  • Sophist Member
  • *
  • Posts: 1,317
  • Gender: Male
  • #!/usr/bin/perl
    • Online Node
PHP Lesson 05 - arrays
« on: August 29, 2003, 05:13:21 PM »
As stated earlier, an array is something that can hold several dynamic values.  This is a case when an array would do more justice than a set of variables:

Code: [Select]
$person1 = 'Parham';
$person2 = 'Jeff';
$person3 = 'Joseph';
$person4 = 'Unknown';
$person5 = 'David';
$person6 = 'Alex';

Why should we have to keep track of all these variables when they all hold the same type of information?  An array can be set using the array() function.  Much like a variable, an array name also starts with a dollar sign.  A simple recode of the above will produce this code (and give you an example of how to declare an array):

Code: [Select]
$people = array('Parham','Jeff','Joseph','Unknown','David','Alex');

Notice instead of declaring a new variable for each name, I've created an array called $people (note the plural word also) and put all the names inside that one array.  Here is how PHP interprets the above array:

$people
[0] => 'Parham';
[1] => 'Jeff';
[2] => 'Joseph';
[3] => 'Unknown';
[4] => 'David';
[5] => 'Alex';

The numbers on the left are known as the "keys" of the array and help keep track of the "values" on the right, inside the array.  The "=>" operator is used to associate the "keys" with the "values" inside the array.  Arrays by convention begin with the 0 "key".  If you have 200 values inside an array, the first "key" will be 0 and the last "key" will be 199.

If you're a programmer that has some OOP language background like Java or C or you don't like using the array() function, you might be more comfortable declaring your arrays like this:

Code: [Select]
$people[] = 'Parham';
$people[] = 'Jeff';
$people[] = 'Joseph';
$people[] = 'Unknown';
$people[] = 'David';
$people[] = 'Alex';

Declaring your arrays like this or with the array() function makes absolutely no difference, this is purely a matter of what you're comfortable with.  If you actually look at the above array() function example, you might realize how similar the above and this example actually are.  This method of declaring an array also exists because PHP uses it internally for HTML form parsing (we'll learn about this in a later lesson).

We [now] know that keys start from 0, this is very important.  We'll now talk about how to retrieve particular values inside these arrays.  Again, I'll show by example rather than try to explain in too much detail:

Code: [Select]
$people = array('Parham','Jeff','Joseph','Unknown','David','Alex'); //declare the array
print $people[0]; //prints "Parham", the first value in the array
print $people[4]; //prints "David"...
print $people[5]; //prints "Alex"...

Easy enough?  I want to take a quick sidestep then and give a quick lesson on printing again.  To print "newlines" (when you press "enter" on your keyboard, the cursor goes to a new line and creates a new hidden character called the "newline" character), you have to use "\n" in your strings.  If you wish to use the "\n" character to skip to the next line, you have to use double quotes.  Example:

Code: [Select]
print "Parham\nteaches\nPHP"; //remember to use double quotes when using the \n characters

That will print:
"Parham
teaches
PHP"

Let's go back to arrays now (sorry about that, the last lesson should have covered the "newline" character as well).  If you want your arrays to be a little more in depth, you can assign your own keys to the array values (This creates associated-arrays because you associate keys with values yourself).  For example:

Code: [Select]
$people = array('person1' => 'Parham','person2' => 'Jeff','person3' => 'Joseph','person4' => 'Unknown','person5' => 'David','person6' => 'Alex');

This would produce:
$people
['person1'] => 'Parham';
['person2'] => 'Jeff';
['person3'] => 'Joseph';
['person4'] => 'Unknown';
['person5'] => 'David';
['person6'] => 'Alex';

REMEMBER that the keys have to be unique; any values that have the same key will be replaced by the most recent value added.  To access specific elements inside our array, we can do this (again by example):

Code: [Select]
$people = array('person1' => 'Parham','person2' => 'Jeff','person3' => 'Joseph','person4' => 'Unknown','person5' => 'David','person6' => 'Alex');
print $people['person1']; //prints "Parham"
print $people['person5']; //prints "David";
print $people['person6']; //prints "Alex";

And that's about it for declaring arrays (sorry about the sidetrack to printing "newlines").
« Last Edit: March 29, 2004, 05:04:24 AM by [Unknown] »

Offline Aquilo

  • The Black Llama
  • SMF Hero
  • ******
  • Posts: 1,518
  • Gender: Male
  • ‹^^› ‹(-_-)› ‹^^›
    • The Arencibia's
Re:PHP Lesson 5
« Reply #1 on: August 29, 2003, 07:02:35 PM »
hehe... >:D
oh nevermind hehe.

Offline Parham

  • SMF Friend
  • Sophist Member
  • *
  • Posts: 1,317
  • Gender: Male
  • #!/usr/bin/perl
    • Online Node
Re:PHP Lesson 5
« Reply #2 on: August 29, 2003, 07:32:55 PM »

Offline Aquilo

  • The Black Llama
  • SMF Hero
  • ******
  • Posts: 1,518
  • Gender: Male
  • ‹^^› ‹(-_-)› ‹^^›
    • The Arencibia's
Re:PHP Lesson 5
« Reply #3 on: August 29, 2003, 07:40:04 PM »
I was going to mess around with folks about associated-arrays and sort()  :D but what I was going to post would have confused folks trying to learn! ;D

[edit] did you get the code I IMed you??
« Last Edit: August 29, 2003, 07:43:15 PM by Aquilo »

Offline Acf

  • SMF Friend
  • SMF Hero
  • *
  • Posts: 3,967
  • Gender: Male
  • 101101010112
Re:PHP Lesson 5
« Reply #4 on: August 30, 2003, 06:08:02 AM »
Parham i like these lessons :) i finally get what array is..  ( i had c++ at school.. the book wasn't that good niter was the teacher)
Sigh...

Offline Parham

  • SMF Friend
  • Sophist Member
  • *
  • Posts: 1,317
  • Gender: Male
  • #!/usr/bin/perl
    • Online Node
Re:PHP Lesson 5
« Reply #5 on: August 30, 2003, 11:13:05 AM »
Parham i like these lessons :) i finally get what array is..  ( i had c++ at school.. the book wasn't that good niter was the teacher)

aww thank you :D:D

Offline Spaceman-Spiff

  • SMF Friend
  • SMF Hero
  • *
  • Posts: 1,524
  • Gender: Male
Re:PHP Lesson 5 - arrays
« Reply #6 on: October 02, 2003, 03:17:29 PM »
what is the proper syntax for returning an array from a function to another blank array var?

Offline Parham

  • SMF Friend
  • Sophist Member
  • *
  • Posts: 1,317
  • Gender: Male
  • #!/usr/bin/perl
    • Online Node
Re:PHP Lesson 5 - arrays
« Reply #7 on: October 02, 2003, 07:26:38 PM »
you can simply just take the return value:

Code: [Select]
$array = something();
foreach ($array as $element) {
  echo $element . "\n";
}

function something() {
return array('1','2','3');
}

would print

Quote
1
2
3

you can also use the list() function on the return statement:

Code: [Select]
list($var1,$var2,$var3) = something();
echo "$var1\n$var2\n$var3";

function something() {
return array('1','2','3');
}

but you'd need to know how many elements are being returned :).  The above example is just like returning an array and then assigning the first three values to variables.

Offline Martje

  • Jr. Member
  • **
  • Posts: 221
  • Gender: Male
    • Hostels Amsterdam
Re:PHP Lesson 5 - arrays
« Reply #8 on: October 21, 2003, 12:35:19 PM »
euhmm I used your example to see what it looks like

<?php

$array = something();
foreach ($array as $element) {
  echo $element . "
";
}

function something() {
return array('1','2','3');
}

?>


but I did not get
1
2
3

I got

1 2 3

on my easyphp

the same for the other examples


is there something wrong with my configuration?

I am reading the examples and try to see the outcome in my head
and then verify it with the easy php server to see if it is the way that i thought.

maime

[edited]

might the right code be this

<?php

$array = something();
foreach ($array as $element) {
  echo $element . "<br>\n";
}

function something() {
return array('1','2','3');
}

?>


he said proudly knowing that taking this lessons are not doing his brains in ;D :P

hehehe I feel having classes again.

but i still have not figured out the function of  "\n" yet to me it does not act like a ENTER it acts like a SPACEBAR
« Last Edit: October 21, 2003, 03:32:06 PM by maime »

Offline writeto

  • Jr. Member
  • **
  • Posts: 341
  • Gender: Male
  • Professional Appreciator
Re:PHP Lesson 5 - arrays
« Reply #9 on: October 21, 2003, 03:46:02 PM »
Maime:

I am going to attempt to clarify something for you. <br> is perfectly ok to use when generating HTML. However, the provided example was suppose to give you a general idea of the use of arrays. \n represent a carriage return, you will use \n when creating a file or formatting output.  The use of echo in this example is as an i/o process in which you are printing $element to the screen, by including \n you are saying you want to place a carriage return (i believe it is ascii 9) that will move the cursor of the current display to the next line (where it will default to the 0 position. <br> is a horse of another color however. <br> is a symbolic reference in html. HTML stands for HyperText Markup Language. It is used to structure output for text and graphics... when your browser is interpretting <br> it is doing exactly the same thing as \n.

I tried to make this simple, if I confused you ignore it.

Andrew
« Last Edit: October 21, 2003, 03:48:14 PM by writeto »

Offline Martje

  • Jr. Member
  • **
  • Posts: 221
  • Gender: Male
    • Hostels Amsterdam
Re:PHP Lesson 5 - arrays
« Reply #10 on: October 21, 2003, 04:20:54 PM »
hey Andrew

thanks for your repley . no its not confusing I now html and I thought <br> had the same function in html as /n in php, but still i dont understand why  I see  ::)

1 2 3
instread of
1
2
3


in the example

$array = something();
foreach ($array as $element) {
  echo $element . "\n";
}

function something() {
return array('1','2','3');
}


would print


Quote
1
2
3


it does not move the 2 or 3 to the next line on position 0.
it does put a space between  1 2 and 3

So I am still wondering what I am missing in this picture. forgive me but I am still a bit of a virgin on the php matters

Offline writeto

  • Jr. Member
  • **
  • Posts: 341
  • Gender: Male
  • Professional Appreciator
Re:PHP Lesson 5 - arrays
« Reply #11 on: October 21, 2003, 05:42:41 PM »
Maime:

I now understand your question much better. If you do a view source on the file generated you will see that it is
1
2
3

this is what he was talking about. You said you know HTML so you know that
<html>
<body>
1
2
3
</body>
</html>
will also generate 1 2 3. This is the output you are receiving. You still need to structure your output in HTML to get the appearance you want.

Andrew

Offline [Unknown]

  • SMF Friend
  • SMF Master
  • *
  • Posts: 36,102
  • Gender: Male
Re:PHP Lesson 5 - arrays
« Reply #12 on: October 21, 2003, 08:49:44 PM »
Actually, \n is 13 and \r is 11.  9 is a tab, or \t.

Right... \n is just like hitting Enter on your keyboard.  If you aren't doing it via html, it will show on separate lines.  Here's an example:

Code: [Select]
<?php
// Tell Internet Explorer that this is a text file not html.
header(&#39;Content-Type: text/plain&#39;);

// Store 1, 2, 3 in an array.
$arr = array(123);

// Print each value on its own line.
foreach ($arr as $val)
   echo 
$val"\n";

?>

-[Unknown]

Offline writeto

  • Jr. Member
  • **
  • Posts: 341
  • Gender: Male
  • Professional Appreciator
Re:PHP Lesson 5 - arrays
« Reply #13 on: October 21, 2003, 09:00:07 PM »
Damn it I can never remember if \n represent 9 or 13... at least I remember that space is 32.

Andrew

Offline dracomiconia

  • Jr. Member
  • **
  • Posts: 300
    • Dracomiconia.com
Re: PHP Lesson 05 - arrays
« Reply #14 on: August 05, 2004, 05:37:54 AM »
Thanks...

I have a question:

Imagine I want to load and array with some indexes.


I am going to make a code, but I'm sure it is going bad:

Code: [Select]

//mysql query, which gives me some results. I charge the array:

$candidato = array(
'id' ,
'datos' => array(
'id_luchador' => $row["ID_REG"],
'fama' => round($row["fama"]/1000,0)+$key+1,
'pais' => $row["pais_escuela"]
),
);


//And finish the query. When I print_r:

print_r($candidato);

//This is the result:

Array ( [id] => 0 [datos] => Array ( [id_luchador] => 1 [fama] => 4 [pais] => Carsa ) )

//But when I make this:

echo "La escuela ".$candidato[0]['id_luchador']." tiene ".$candidato[0]['fama']." y es del pais ".$candidato[0]['pais'];

//The result is:

La escuela tiene y es del pais

Where is it bad? And how can I arrange it?
« Last Edit: August 05, 2004, 06:17:21 AM by dracomiconia »

Offline dracomiconia

  • Jr. Member
  • **
  • Posts: 300
    • Dracomiconia.com
Re: PHP Lesson 05 - arrays
« Reply #15 on: August 05, 2004, 06:26:34 AM »
I'll answer myself:

Code: [Select]

//Mysql query... Charging array:


$candidato [] = array(
'datos' => array(
'id_luchador' => $row["ID_REG"],
'fama' => round($row["fama"]/1000,0)+$key+1,
'pais' => $row["pais_escuela"]
),
);


// End of mysql... echo:

echo "La escuela ".$candidato[0]['datos']['id_luchador']." tiene ".$candidato[0]['datos']['fama']." y es del pais ".$candidato[0]['datos']['pais'];


//Gives:

La escuela 1 tiene 4 y es del pais Carsa



Offline [MiNX]Tek

  • Semi-Newbie
  • *
  • Posts: 37
  • Gender: Male
  • Tek of MiNX Media, Ltd.
    • MiNX Media, Ltd.
Re: PHP Lesson 05 - arrays
« Reply #16 on: September 11, 2004, 06:55:07 PM »
Okay... I understood the first post. Kinda knew what you were talking about (never contemplated what an "array" was) but... what would we (forum people) use arrays for?

Offline [Unknown]

  • SMF Friend
  • SMF Master
  • *
  • Posts: 36,102
  • Gender: Male
Re: PHP Lesson 05 - arrays
« Reply #17 on: September 11, 2004, 06:57:37 PM »
If you've looked at a template in SMF, everything - and I do mean everything - is stored with arrays.  That's how SMF communicates with the theme.

-[Unknown]

Offline Joey Smith™

  • SMF Friend
  • SMF Hero
  • *
  • Posts: 6,356
  • Gender: Male
Re: PHP Lesson 05 - arrays
« Reply #18 on: November 23, 2008, 11:10:44 PM »
If you've looked at a template in SMF, everything - and I do mean everything - is stored with arrays.  That's how SMF communicates with the theme.

-[Unknown]
Oh, how well I am learning this..... Makes my head hurt lmao..

Offline GreenX

  • Semi-Newbie
  • *
  • Posts: 15
Re: PHP Lesson 05 - arrays
« Reply #19 on: April 06, 2009, 07:31:18 AM »
I have the following array setup:

Code: [Select]
$fielddef =
  array(
array(
      'caption' =>      "Character Name",
      'name' =>         "charname",
      'type' =>         "text",
      'options' =>      "",
      'defaultvalue' => "",
      'required' =>     1   
    ),

then in another section under it
Code: [Select]
      $msgOptions = array(
        'id' =>  0 ,
        'subject' => '[NEW] Application from ' . $fielddef["charname"],
        'body' => $postbody ,
        'icon' => 'xx',
        'smileys_enabled' => true,
        'attachments' =>  array(),
      );

Basically its to create the subject of a post but using $fielddef["charname"] OR $fielddef['charname'] doesn't reference that field I want, its just blank.

How do I reference that array for that data of charname?

Thanks!