You are here: Re: Technique for creating variables within a loop « All PHP « IT news, forums, messages
Re: Technique for creating variables within a loop

Posted by d43m0n AT shaw DOT ca on 08/06/06 07:42

Dave wrote:
> Hi,
> I'm reasonably proficient in PHP but have been asked how to do
> something which has got me stumped. Hence, my posting:
>
> I want to create a small number of variables, $pos1, $pos2 ... $pos5
> within a loop and assign them values from an array, but creating the
> variable names with incrementing numbers, well I've no idea how the PHP
> syntax for it works.
>
> ========== START CODE ==========
> <?php
>
> $x=5;
> $myarray = array('a','b','c','d','e');
>
> for($a=0;$a<$x;$a++){
> $pos.$a = $myarray[$a]; //Create $pos0 here on first loop,
> // $pos1 next loop and so forth..
> }
>
> //Test assigned variable
> echo $pos3; // $pos3 should equal 'd'
> exit;
>
> ?>
>
> ========== END CODE ==========
>
> Any ideas?

Personally, your doing it all wrong...

Use foreach, since you've already got your key and your item defined...
and all you need is to generate generic varibles... the only way to do
that is to use this function ${'varname'};

<?php

$array = array('0' => 'a', '1' => 'b', '2' =>'c', '3' =>'d', '4'=>'e');


foreach ($array as $key => $item) {
${'pos' . $key} = $item;
}

echo $pos3; // $pos3 should equal 'd'
die();

?>

Don't forget... read the manual before asking questions...

~ Daemon

 

Navigation:

[Reply to this message]


Удаленная работа для программистов  •  Как заработать на Google AdSense  •  England, UK  •  статьи на английском  •  PHP MySQL CMS Apache Oscommerce  •  Online Business Knowledge Base  •  DVD MP3 AVI MP4 players codecs conversion help
Home  •  Search  •  Site Map  •  Set as Homepage  •  Add to Favourites

Copyright © 2005-2006 Powered by Custom PHP Programming

Сайт изготовлен в Студии Валентина Петручека
изготовление и поддержка веб-сайтов, разработка программного обеспечения, поисковая оптимизация