user1353519
user1353519

Reputation: 71

print php for each values in variable

I am very new to php.I have a foreach loop

foreach ($sizes as $w => $h) {

echo 'index is '.$w.' and value is '.$h;}

I need to assigning these values (I have 2 values) in to variables

$firstItem = foreach value 1

$secondItem = foreach value 2

How can I do this Thanks

Upvotes: 0

Views: 91

Answers (5)

user2849211
user2849211

Reputation:

I think you should do this.

list($firstVariable,secondVariable) = $sizes;

Upvotes: 1

chiliNUT
chiliNUT

Reputation: 19573

you could try something like this

//what is in "sizes"?
$sizes=array('a'=>'foo',
             'b'=>'bar');    

foreach ($sizes as $w => $h) {
${"item".$w}=$h;
}

echo "item a is ".$itema //item a is foo
echo "item b is ".$itemb //item b is bar

Upvotes: 0

BlackWhite
BlackWhite

Reputation: 832

foreach ($sizes as $w => $h) {

$firstItem = $sizes[$w1];
$secondItem = $sizes[$w2];
}

where $w1 is first key AND $w2 is second key

Upvotes: 1

Dalım Çepiç
Dalım Çepiç

Reputation: 513

According to comment of Tamil Selvan

<?php
$sizes = array("5","10");
list($firstItem, $secondItem) = $sizes;
echo $firstItem." - ".$secondItem;
?>

The result like

5 - 10

Upvotes: 0

Tamil Selvan C
Tamil Selvan C

Reputation: 20199

Use list() function as

list($firstItem, $secondItem) = $sizes;
echo $firstItem , ' ', $secondItem;

Upvotes: 2

Related Questions