[SOLVED] array - printing key and value

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
malcolmboston
DevNet Resident
Posts: 1826
Joined: Tue Nov 18, 2003 1:09 pm
Location: Middlesbrough, UK

[SOLVED] array - printing key and value

Post by malcolmboston »

i have this array

Code: Select all

Array
(
    [Silas] => 20
    [OTS] => 1
    [MK Yen] => 1
    [Carhartt] => 1
    [Marshall Artist] => 1
)
now i need to print

Silas: 20
OTS: 1

in this format however no matter what i do, its just not working, can someone prod me in the right direction please?
Last edited by malcolmboston on Thu Oct 26, 2006 8:36 am, edited 1 time in total.
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

Code?
malcolmboston
DevNet Resident
Posts: 1826
Joined: Tue Nov 18, 2003 1:09 pm
Location: Middlesbrough, UK

Post by malcolmboston »

Code: Select all

$c =1;
   foreach ($newStockArray as $v) {
      echo ''.$newStockArray[$c].' => '.$v.'';
      $c++;
   }
i dont usually hold arrays like this, ive never used foreach and the manual for that page is sketchy at best
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

Okay, so $newStockArray is the array output above?

$newStockArray['Sila'] and $newStockArray['OTS'] would be the references to use, not numeric indexing. Now, if $v is the above array the references would be very similar, and one could use

Code: Select all

foreach($newStockArray as $c => $v)
{
  echo $v['Sila'];
}
for example.
malcolmboston
DevNet Resident
Posts: 1826
Joined: Tue Nov 18, 2003 1:09 pm
Location: Middlesbrough, UK

Post by malcolmboston »

this is basically a for loop, so would i need to do array_keys and then echo the key dynamically?
malcolmboston
DevNet Resident
Posts: 1826
Joined: Tue Nov 18, 2003 1:09 pm
Location: Middlesbrough, UK

Post by malcolmboston »

NvM

Code: Select all

$newStockKeys = array_keys ($newStockArray);
      $c = 0;
   foreach ($newStockArray as $v) {
      // get percentage
      $percentageBrand = number_format((($v / $totalItems) * 100), 2);
      echo ''.$newStockKeys[$c].': '.$v.' <strong>'.$percentageBrand.'%</strong><br>';
      $c++;
   }
it just seems like a really long way of doing something that should be so simple :S
User avatar
volka
DevNet Evangelist
Posts: 8391
Joined: Tue May 07, 2002 9:48 am
Location: Berlin, ger

Post by volka »

Code: Select all

<?php
$a = array(
    'Silas' => 20,
    'OTS' => 1,
    'MK Yen' => 1,
    'Carhartt' => 1,
    'Marshall Artist' => 1,
	);
	
foreach($a as $i=>$v) {
	echo $i, ': ', $v, "<br />\n";
}
?>
Post Reply