Page 1 of 1

Concatenate an array into a variable

Posted: Thu May 15, 2003 10:19 am
by FredEH
Hi, I searched for this and couldn't find it. Any help would be terrific :)

Should I be able to do something like this:

Code: Select all

<?php
$array = array("h","e","l","l","o");
$i=0;
while($array)
{
    $var .= $array[$i];
    $i++;
}
print $var;
?>
This is just a simplified version of what I'm trying to do. My array is much larger than this example and I need to combine certain elements of the array to single variables. I tried the above code and its not working.

Thanks in advance.

Posted: Thu May 15, 2003 10:24 am
by volka
while( <condition> ) runs as long as <condition> evaluate to true.

You might use foreach() or even simpler join()/implode()

Posted: Thu May 15, 2003 10:32 am
by Gleeb
To join the entire array, use implode.

To join only certain parts, maybe something like this could help...

Code: Select all

<?php
$array=array("H","e","l","l","o");
$otherarray=array();
$usethis=array(TRUE,TRUE,TRUE,TRUE,FALSE);
$i=0; // Do you have to initilise variables? I can never remember
for ($j=0;$j<5;$j++)
{
   if ($usethis[j]) $otherarray[i++]=$array[j];
}
$thestring = implode('',$otherarray);
?>
Horrid code, isn't it? But it's an (untested) example.

Posted: Thu May 15, 2003 10:48 am
by FredEH
Thanks for the replies.

Volka,
I definately need to understand implode better, but I do need to combine certain elements into variables so implode alone I don't think will work.

Gleeb,
I think that will work. I'll try it out and let you know.

Thanks again.

Posted: Thu May 15, 2003 10:59 am
by volka
ah, sorry, didn't read the
and I need to combine certain elements of the array to single variables
part of your question :oops:
as compensation I offer you two other links (generous, isn't it :lol: ) you might find interesting.
http://www.php.net/manual/en/function.array-reduce.php
http://www.php.net/manual/en/function.array-filter.php

Posted: Thu May 15, 2003 11:13 am
by FredEH
aha.... very cool.

Thanks so much! :)

Posted: Thu May 15, 2003 3:54 pm
by Heavy
Gleeb wrote:$i=0; // Do you have to initilise variables? I can never remember
Reading an uninitialised variable gererates a warning.
It shows as a warning message if ini-setting:

Code: Select all

error_reporting = E_ALL
If you want to turn that off in portable scripts:

Code: Select all

<?php
ini_alter("error_reporting","E_ALL & ~E_NOTICE"); 
//put this before reading any variables.
?>

Posted: Fri May 16, 2003 2:21 am
by twigletmac
Although fixing errors is always better than hiding them...

Mac