954,576 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Array within an array

i have to access an array within an array using php, and i have very little experience working with php.

can anyone point me towards a good tutorial or show me an example of how to go about it?

eg:

[0] contians [a],[b],[c]

many thanks

EvilOrange
Light Poster
30 posts since Jan 2009
Reputation Points: 10
Solved Threads: 0
 
$somearray = array(
  array('a' => 'Hello'),
  array('b' => 'World')
);

echo $somearray[0]['a'] . ' ' . $somearray[1]['b'];
// Hello World
ShawnCplus
Code Monkey
Team Colleague
1,583 posts since Apr 2005
Reputation Points: 526
Solved Threads: 268
 
<?php
  // Set array parts
  $a = array("1" => "one", "2" => "two");
  $b = array("a" => "aye", "b" => "bee");
  $c = array("a scalar", $a, $b);

  // Extract a sub-element from an array in the array
  $d = $c[1][2];

  // Extract a sub-array from the array
  $e = $c[2];

  // Display the various demonstration bits
  print "<pre>\n\$c[2] = ";
  print_r ($c[2]);
  print "</pre>\n\n";
  print "\$c[2]['b'] = {$c[2]['b']}\n\n";
  print "<pre>\n\$c[1] = ";
  print_r ($c[1]);
  print "</pre>\n\n";
  print "\$d = $d\n\n";
  print "<pre>\n\$e = ";
  print_r ($e);
  print "</pre>\n\n";
  print "\$c[0] = $c[0]\n";
?>


Watch the syntax when printing. PHP's parser is a little dicey in that situation; arrays often need to be braced when printing directly.

Fest3er
Posting Whiz in Training
242 posts since Aug 2007
Reputation Points: 51
Solved Threads: 35
 

thanks for the advice

so using the first example:

if [0] had [a][b][c]

all i'd need to do to access an array and assign the contents to vars would be (using first example):

$avar = $somearray[0]['a'];
$bvar = $somearray[1]['b'];

echo $avar;
echo $bvar;

// Hello
// World
EvilOrange
Light Poster
30 posts since Jan 2009
Reputation Points: 10
Solved Threads: 0
 

thanks for the advice

so using the first example:

if [0] had [a][b][c]

all i'd need to do to access an array and assign the contents to vars would be (using first example):

$avar = $somearray[0]['a'];
$bvar = $somearray[1]['b'];

echo $avar;
echo $bvar;

// Hello
// World

Precisely. If you want to get really deep into how arrays work take a look at the language documentation. http://php.net/arrays

ShawnCplus
Code Monkey
Team Colleague
1,583 posts since Apr 2005
Reputation Points: 526
Solved Threads: 268
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You