• Welcome to Simple Machines Community Forum. Please login or sign up.
January 20, 2022, 06:30:15 AM

News:

SMF 2.1 RC4 has been released! Try it out and help us test! :) Read more.


PHP Lesson 05 - arrays

Started by Parham, August 29, 2003, 05:13:21 PM

Previous topic - Next topic

Parham

August 29, 2003, 05:13:21 PM Last Edit: March 29, 2004, 05:04:24 AM by [Unknown]
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:


$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):


$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:


$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:


$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:


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:


$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):


$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").

Aquilo

hehe... >:D
oh nevermind hehe.

Parham


Aquilo

August 29, 2003, 07:40:04 PM #3 Last Edit: August 29, 2003, 07:43:15 PM by Aquilo
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??

Acf

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...

Parham

Quote from: Aliencowfarm 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)

aww thank you :D:D

Spaceman-Spiff

what is the proper syntax for returning an array from a function to another blank array var?

Parham

you can simply just take the return value:


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

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


would print

Quote1
2
3

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


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.

Martje

October 21, 2003, 12:35:19 PM #8 Last Edit: October 21, 2003, 03:32:06 PM by maime
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

writeto

October 21, 2003, 03:46:02 PM #9 Last Edit: October 21, 2003, 03:48:14 PM by writeto
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

Martje

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

writeto

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

[Unknown]

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:

<?php
// Tell Internet Explorer that this is a text file not html.
header('Content-Type: text/plain');

// 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]

writeto

Damn it I can never remember if \n represent 9 or 13... at least I remember that space is 32.

Andrew

dracomiconia

August 05, 2004, 05:37:54 AM #14 Last Edit: August 05, 2004, 06:17:21 AM by dracomiconia
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:



//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?

dracomiconia

I'll answer myself:



//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




[MiNX]Tek

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?

[Unknown]

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]

Joey Smith™

Quote from: [Unknown] 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]
Oh, how well I am learning this..... Makes my head hurt lmao..

GreenX

I have the following array setup:


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


then in another section under it

      $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!

Advertisement: