0

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

2
  • 1
    use list($firstItem, $secondItem) = $sizes Commented Oct 13, 2013 at 17:06
  • What values do you want to assign? Can you show $sizes structure? Commented Oct 13, 2013 at 17:09

5 Answers 5

2

Use list() function as

list($firstItem, $secondItem) = $sizes;
echo $firstItem , ' ', $secondItem;
Sign up to request clarification or add additional context in comments.

Comments

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

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

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

1 Comment

Here is the full function.This is an image re size function.once image uploaded this will generate 2 images.But I need to assing these 2 images in separate variables if( $_FILES['image']['size'] < $max_file_size ){ // get file extension $ext = strtolower(pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION)); if (in_array($ext, $valid_exts)) { /* resize image */ foreach ($sizes as $w => $h) { echo $files[i] = resize($w, $h0); } } else { $msg = 'Unsupported file'; }
1

I think you should do this.

list($firstVariable,secondVariable) = $sizes;

Comments

0

According to comment of Tamil Selvan

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

The result like

5 - 10

Comments

0

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

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.