Please help me get my head around multidimensional arrays in PHP.
November 23, 2005 8:31 AM   Subscribe

Please help me get my head around multidimensional arrays in PHP.

I'm trying to create an array that will store phone numbers. Each number has a group of attributes including:

* Type - (i.e. Mobile, home, etc)
* Number - (the actual number itself)
* Extension (will frequently be null)
* Is Preferred - (is this their primary contact number)

I would like to be able to create this array, and access it via named indexes the same way I access a multi-column array that I pull out of a MySQL database. In fact, my ultimate goal is to check this data and insert it into a MySQL table when I don't know in advance how many rows of data I'll be working with.

I understand that the syntax will be different (probably using a foreach or list or someting), but basically:

while ($row = mysql_fetch_array ($Phone_Numbers, MYSQL_ASSOC)) {
echo $Phone_Numbers['type'] . $Phone_Numbers['number'] . $Phone_Numbers['ext'] . $Phone_Numbers['preferred'] ;
}

I've tried various ways of creating and accessing this array, but none have worked quite like I'd hoped. It seems that either I get an array where I'm overwritting the values of each index with each row of data I try to put in, or I get an array that is so deep and complex that the data is in there, but I don't know how to retrieve it.

So, given:
$phoneType1, $phoneNumber1, $phoneExt1, $phonePreferred1

--AND--
$phoneType2, $phoneNumber2, $phoneExt2, $phonePreferred2

--AND--

[...]

How do I create the array, and how do I retrieve data from the array by index?
posted by willnot to Computers & Internet (20 answers total)
 
I don't know much about PHP, but why don't you create an array of phone number objects that contain all those attributes?

No sane OOP programmer would try this. Nor would functional programmers, they'd use structs.

Careful or you'll show up on the Daily WTF.
posted by jon_kill at 8:39 AM on November 23, 2005


Are you sure you wouldn't rather do this some other way? Like store it in a database? That's what this sort of task is meant to be done by.

If you must do this in a data structure, might I suggest an array of hashes? Are you familiar with hashes? If so, I'll get more into it - if not, I won't bore you with a big slop of code ;-)

But.. to address your array of arrays question:

This page should help you...
posted by twiggy at 8:40 AM on November 23, 2005


Hmm, I totally missed your spot on the fact you're already pulling it out of a mysql database.. duh... sorry!

Anyway, the page I linked should help you. You really want an array of hashes though...
posted by twiggy at 8:42 AM on November 23, 2005


I agree with jon_kill. You want to do something like this (untested):

class PhoneNumber {
var $type;
var $number;
// ...
}

$numbers = array();
$numbers[0] = new PhoneNumber();
$numbers[0]->type = "mobile";
$numbers[0]->number = "555-1212";
$numbers[1] = new PhoneNumber();
$numbers[1]->type = "fax";
$numbers[1]->number = "123-4567";
// ...

foreach ($numbers as $n) {
echo $n->type . $n->number;
}

If you want a real working example, check out this file and this one from a PHP web site I once wrote.
posted by mbrubeck at 8:45 AM on November 23, 2005


I'm not pulling it out of a data base. i'm recieving a number of phone numbers from a web page, and I want to check the numbers and then insert them into the database.

The problem is that I don't know in advance how many numbers I'll have to work with, so i wanted to iterate through them as long as I had them, and an array is the only way I know how to do that.

I have no idea what I'm doing with this stuff. I'm absolutely postive there are 50 better ways to do it. But, given that all I have is a hammer, everything looks like a big, very hard to hit nail.

I have no idea what hashes are, and while I sort of understand OOP at a conceptual level, I have no experience with it and understood that OOP was painful in PHP anyway. Even functions are a bit out of my range. I can read through one that's been created and sort of get an idea for what it will do, but creating one myself would be a challenge.
posted by willnot at 8:47 AM on November 23, 2005


If you're dead-set on using an array for this, what's wrong with the one PHP gives you back when you make a database query? Assuming you assign the result of the query to an array called $aResults:

for ($i = 0; $i < count($aresults); $i++)br> {
echo $aResults[$i]["column_name"];
}

will give you what you want (I think).
posted by yerfatma at 8:50 AM on November 23, 2005


Upon submission, that's obviously not what you want. How are you receiving the numbers from a web page? Screen scraping them?
posted by yerfatma at 8:50 AM on November 23, 2005


$phone_numbers[1][type] = "";
$phone_numbers[1][number] = "";
$phone_numbers[1][extension] = "";
$phone_numbers[2][type] = "";
$phone_numbers[2][number] = "";
$phone_numbers[2][extension] = "";
posted by ajbattrick at 8:51 AM on November 23, 2005



I have no idea what hashes are, and while I sort of understand OOP at a conceptual level, I have no experience with it and understood that OOP was painful in PHP anyway. Even functions are a bit out of my range. I can read through one that's been created and sort of get an idea for what it will do, but creating one myself would be a challenge.


Maybe you should read up a bit on procedural programming, and the language you're programming in, specifically. That might help.
posted by jon_kill at 8:53 AM on November 23, 2005


print_r() is a great way to get a handle on how PHP deals with data structures, especially multi-dimensional arrays.
posted by revgeorge at 8:56 AM on November 23, 2005


I have a web page form where the user will enter their phone number(s). The page will start out with a few rows, and if the user has additional numbers they want to enter, the form will create new rows of form inputs.

So, ultimately, the page does know how many numbers it's dealing with which I can assign as a variable, but I don't know how many rows of inputs I'll need to iterate through.

So basically, the page woudl look like

Preferred:
type [ ....] number________ ext ___

Alternate
type [....] number_________ ext ___
type [....] number_________ ext ___
Add Additional Numbers

[submit]

I need to be able to check each number and insert it into a database. I'm not dead set on doing it with any particular method.

I will definitely try what mbrubeck has suggested.

Thanks
posted by willnot at 8:59 AM on November 23, 2005


Form
First, you need to set your form up to handle the different numbers for use in processing. If you know how many fields there are, you could do something like:

$num_of_entries = 5;
for($i=0; $i < $num_of_entries; $i++) {br>   $form = '
  <input name="phone[$i][type]">
  <input name="phone[$i][number]">
  <input name="phone[$i][extension]">
  <input name="phone[$i][preferred]">
  ';
  // Note: code doesn't work as-is... needs to be integrated
  // within HTML of your form

}
echo $form;

Action Page
When it comes to processing these variables (assuming your form's "method" is set to post), all of the values will be stored in the $_POST array. Specifically... the $_POST['phone'] part of the array (The post data is just one huge multi-dimensional array).

To iterate through the phone numbers, simply use a foreach...

foreach ($_POST['phone'] as $key => $value) {
  // You can do anything with the values here
  // For instance, just display them to the user...
  echo "Phone entry #".$key;
  echo "Type: ".$value['type'];
  echo "Number: ".$value['number'];
  echo "Extension: ".$value['extension'];
  echo "Preference: ".$value['preference'];

  // Or you could enter them into a MySQL db
  // Like so...
  $sql = "INSERT INTO table_name VALUES (
    '".$value['type']."',
    '".$value['number']."',
    '".$value['extension']."',
    '".$value['preference']."'
  );
  $result = mysql_query($sql);
}

posted by Hankins at 9:45 AM on November 23, 2005


mbrubeck - solution worked.

ajbattrick and Hankins - I didn't realize you could string those[] index names together like that.

So Hankins - it seems like your solution saves me the step of reading the various $_POST variables and then putting them into the array or class or whatever. For that reason, I'm assuming your method would be the preferable way to do it in this case

I'll test it and make sure, but just so I understand better, when would I want to use a class instead?

And Jon_Kill - no doubt, I still have much to learn. if you have any books or web pages you'd like to direct me towards, that would be helpful.

Thanks
posted by willnot at 9:58 AM on November 23, 2005


I have no idea what hashes are

Ever so slightly off-topic, but you *must* learn about hashes! They are immensely useful for all sorts of real-world programming situations. And they're really not difficult if you understand arrays.

Basically, a hash is just a different type of array where, instead of the indexes being numbers (the 0th element, the 1st element, the 99th element etc), they are strings. So you can say "Give me the value in the 'type' element", "Give me the value in the 'number' element" and so on. If nothing else, it saves you having to remember that element 0 is the type, element 1 is the name, element 2 is the number etc.
posted by littleme at 9:59 AM on November 23, 2005


Just to mention: Hankins' form code won't work exactly as shown, because he's trying to interpolate variable names within a single-quoted string, which doesn't work. Not difficult to fix, though.
posted by littleme at 10:01 AM on November 23, 2005


littleme: In PHP, hashes are known as "Associative Arrays." PHP arrays are really convenient in that you can access them both by the key index and by the name index. example:

< ? br> $array['foo'] = bar;
echo $array[0].'
';
echo $array['foo'];
?>

will print

bar
bar

posted by SpecialK at 12:01 PM on November 23, 2005


Hmn. Forgot to use LT and GT tags, but you get the idea. Sorry about the foobed code, it looked fine in preview.
posted by SpecialK at 12:02 PM on November 23, 2005


Well, yes, but to many people (esp. Perl programmers) 'hash' and 'associative array' are synonymous. (Actually, I don't like the fact that you can do what you describe in PHP -- I'd rather see associative arrays done as real hashes, with the extra speed that provides.)

/derail
posted by littleme at 3:20 PM on November 23, 2005


Not knowing about hashes in PHP is kind of like asking, "I'm using this hammer, but I put in a nail in a place where I don't want it. I'd like to remove it, but don't know how. I have seen this claw thing on the other end of the hammer, but I haven't read about that yet."

In other words... get thee to php.net or to a bookstore. You will find that the time you invest in reading is more than made up for by not having to go down the road of implementing everything "the hard way" and suffering along with the resulting bad code.
posted by Rhomboid at 7:29 PM on November 23, 2005


...for example...
posted by Rhomboid at 7:31 PM on November 23, 2005


« Older My Wife Needs a Hand   |   Microsoft CMS and/or Wikis Newer »
This thread is closed to new comments.