Robert
Robert

Reputation: 147

PHP separate Foreach loop values and store to variables

Hello I have an array and a foreach loop, which is technically working fine. Here is my code.

foreach ($results as $result) {
    $data['manrat'][] = array(
        'manufacturer' => $result['manufacturer'],
        'mhref'        => $this->url->link('/info', 'manufacturer_id=' . $result['manufacturer_id'])
    );
}

And

<?php foreach($manrat as $manrate) { ?>
    <a href="<?php echo $manrate['mhref']; ?>"><?php echo $manrate['manufacturer'];?> </a>
<?php } ?>

This is give me a result like this:

name1 name2 name3 name4 name5

I would like to store each name to different variables. This is possible?

Upvotes: 1

Views: 3345

Answers (3)

mamal
mamal

Reputation: 1976

use implode and if you want turn String to Array use explode

$array_to_string = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];
$store_to_string =  implode(',',$array_to_string ); // a,b,c,d,e,f,g

Upvotes: 0

I would refactor this code into one foreach loop like this:

$anchors = '';

foreach ($results as $result) {
    $anchors .= '<a href="' . $this->url->link('/info', 'manufacturer_id=' . $result['manufacturer_id']) . '">' . $result['manufacturer'] . '</a>';
}

and on your actual HTML output page:

<?php echo $anchors ?>

Upvotes: 0

Ketan Malhotra
Ketan Malhotra

Reputation: 1250

I don't quite understand your question properly but if this is what you mean, then here's my answer. You can just store to different variable or an array like names[] by adding the assigning code in your loop like:

<?php
$names = array();
foreach($manrat as $manrate) {
 $names[] = $manrate['manufacturer'];
}
?>

You can then get the names as elements of the array like: $names[0], $names[1], ... etc.

I hope this answered your question.

Upvotes: 2

Related Questions