0

I'm stuck in my self learning PHP because of the array looping.

Let's say I have two arrays, same number of elements:

$description
: array = 
  0: string = Name
  1: string = LastName
  2: string = Address
  3: string = City
  4: string = Country

 $value
: array = 
  0: string = Dan
  1: string = Smith
  2: string = 4, Burlington St
  3: string = London
  4: string = England

What should I do to print the following? :

Name: Dan
LastName: Smith
Address: 4, Burlington St
City: London
Country: England

1
  • 3
    Since you're learning, this is a great time to learn that PHP's associative array handling is better suited to something like array('name'=>'Dan', 'LastName'=>'Smith','Address'=>'...',....) Commented Jul 9, 2013 at 11:05

4 Answers 4

5

You can use array_combine to merge these two arrays into one:

$c = array_combine($description, $value);
foreach ($c as $key => $value) {
   echo $key . ": " . $value;
}
Sign up to request clarification or add additional context in comments.

Comments

1

Option #1:

foreach($description as $key => $descText) {
    echo $descText, ': ', $value[$key], PHP_EOL;
}

Option #2

$mi = new MultipleIterator();
$mi->attachIterator(new ArrayIterator($description));
$mi->attachIterator(new ArrayIterator($values));
foreach($mi as $detail) {
    list($descText, $descValue) = $detail;
    echo $descText, ': ', $descValue, PHP_EOL;
}

2 Comments

#2 is nice, but a bit like shooting a fly with a cannon
errata fixed - and while it is a sledgehammer, I still like MultipleIterators on principle, especially when working with mismatched indexes (not the case here, I know)
0

Try

for ($i = 0; $i < count($description); $i++) {
    echo $description[$i] . ': '.$value[$i] . '<br/>';
}

Comments

0

Try like

$new_arr = array();
for(int i=0;i<count($description);$i++) {
    $new_arr[$description] = $value;
}

Now

foreach($new_arr as $key => $val) {
    echo $key . ':' .$val.'<br>';
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.