1.11M Members

Array within an array

 
0
 

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],,[c]

many thanks

 
0
 
$somearray = array(
  array('a' => 'Hello'),
  array('b' => 'World')
);

echo $somearray[0]['a'] . ' ' . $somearray[1]['b'];
// Hello World
 
0
 
<?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']}<br>\n\n";
  print "<pre>\n\$c[1] = ";
  print_r ($c[1]);
  print "</pre>\n\n";
  print "\$d = $d<br>\n\n";
  print "<pre>\n\$e = ";
  print_r ($e);
  print "</pre>\n\n";
  print "\$c[0] = $c[0]<br>\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.

 
0
 

thanks for the advice

so using the first example:

if [0] had [a][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
 
0
 

thanks for the advice

so using the first example:

if [0] had [a][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

Question Answered as of 5 Years Ago by ShawnCplus and Fest3er
You
This question has already been solved: Start a new discussion instead
Post:
Start New Discussion
Tags Related to this Article