Danferth
Danferth

Reputation: 1879

looping through arrays with foreach statement

I have a list of arrays and need them to output with a printf statement

<?php
$example = array("first" => "Bob", "last" => "Smith", "address" => "123 Spruce st" );
$example = array("first" => "Sara", "last" => "Blask", "address" => "5678 Maple ct" );

foreach ($example as $key => $val) {
  printf("<p>hello my name is %s %s and i live at %s</p>",$example['first'],$example['last'], $example['address']);
}

?> 

The above just outputs the last array, i need it to loop through all of the arrays and produce a <p> with the supplied key => value combinations. this is only a simplified example as the real world code will be more complex in the outputted html

I tried

foreach ($example as $arr){
printf("<p>hello my name is %s %s and i live at %s</p>",$arr['first'],$arr['last'], $arr['address']);
}

but it only outputs a single character for each key => value

Upvotes: 0

Views: 362

Answers (4)

sbeliv01
sbeliv01

Reputation: 11810

You'll have to make an array of your arrays and loop through the main array:

<?php

$examples[] = array("first" => "Bob", "last" => "Smith", "address" => "123 Spruce st" );
$examples[] = array("first" => "Sara", "last" => "Blask", "address" => "5678 Maple ct" );

foreach ($examples as $example) {
  printf("<p>hello my name is %s %s and i live at %s</p>",$example['first'],$example['last'], $example['address']);
}

?> 

Upvotes: 0

Explosion Pills
Explosion Pills

Reputation: 191729

You're overwriting $example on both lines. You need a multi-dimensional "array of arrays:"

$examples = array();
$examples[] = array("first" ...
$examples[] = array("first" ...

foreach ($examples as $example) {
   foreach ($example as $key => $value) { ...

Of course, you can also do the printf immediately instead of assigning the arrays.

Upvotes: 0

Bugs
Bugs

Reputation: 1452

You need to declare example as an array as well to get a 2-dimensional array and then append to it.

$example = array();
$example[] = array("first" => "Bob", "last" => "Smith", "address" => "123 Spruce st" ); # appends to array $example
$example[] = array("first" => "Sara", "last" => "Blask", "address" => "5678 Maple ct" );

Upvotes: 1

nickb
nickb

Reputation: 59699

Try something like this:

// Declare $example as an array, and add arrays to it
$example = array();
$example[] = array("first" => "Bob", "last" => "Smith", "address" => "123 Spruce st" );
$example[] = array("first" => "Sara", "last" => "Blask", "address" => "5678 Maple ct" );

// Loop over each sub-array
foreach( $example as $val) {
    // Access elements via $val
    printf("<p>hello my name is %s %s and i live at %s</p>",$val['first'],$val['last'], $val['address']);
}

You can see from this demo that it prints:

hello my name is Bob Smith and i live at 123 Spruce st
hello my name is Sara Blask and i live at 5678 Maple ct

Upvotes: 2

Related Questions