tags:

views:

37

answers:

5

This is an array i have

<?php
$page['Home']='index.html';
$page['Service']='services.html';
?>

How do i get to echo something like this for individual one like

Home is at index.html

and again how can i do this through a loop and echo all?

+4  A: 
foreach($page as $key => $value) {
  echo "$key is at $value";
}

For 'without loop' version I'll just ask "why?"

Mchl
This is fine... just wanted to know if it possible to get a value individually by referring it to as 0 or 1 etc... I have just started with these stuffs. Thank You very much!!
esafwan
that's a very common thing actually, to address an array items individually.
Col. Shrapnel
Oh, OK. I understood your question as 'how to echo all key-value elements from an array without using a loop' - which would be silly thing to do IMHO (unless using array_walk like KennyTM did).
Mchl
+2  A: 

If you must not use a loop (why?), you could use array_walk,

function printer($v, $k) {
   echo "$k is at $v\n";
}

array_walk($page, "printer");

See http://www.ideone.com/aV5X6.

KennyTM
A: 
function displayArrayValue($array,$key) {
   if (array_key_exists($key,$array)) echo "$key is at ".$array[$key];
}

displayArrayValue($page, "Service"); 
Mark Baker
+1  A: 

for the first question

$key = 'Home';
echo $key." is at ".$page[$key];
Col. Shrapnel
A: 

Without a loop, just for the kicks of it...


You can either convert the array to a non-associative one, by doing:

$page = array_values($page);

And then acessing each element by it's zero-based index:

echo $page[0]; // 'index.html'
echo $page[1]; // 'services.html'

Or you can use a slightly more complicated version:

$value = array_slice($page, 0, 1);

echo key($value); // Home
echo current($value); // index.html

$value = array_slice($page, 1, 1);

echo key($value); // Service
echo current($value); // services.html
Alix Axel