Jump to content

foreach simple question


robert_gsfame

Recommended Posts

How can i put foreach result in a string, so let say i have 1 2 3 and separated with ";" so it goes 1;2;3 and i want to put it as $value...how to do??

 

foreach($val as $indeks)

$choice="";

for($i=0;$i<count($val);$i++){

$choice=$choice.$val[$i].";";

}

echo $choice;

 

this give me wrong result..

Link to comment
https://forums.phpfreaks.com/topic/200239-foreach-simple-question/
Share on other sites

First off, you are assigning $indeks to equal the current $val, but then you use $val.

 

foreach ($indeks as $val)
{
   $choice="";

   for ($i=0; $i<count($val); $i++) {
      $choice=$choice.$val[$i].";";
   }

   echo $choice;
}

 

This may not work, but you did not show the entire relevant code. Having the for loop in the for loop doesn't make sense for what you asked for.

 

Also, indent code and add spacing accordingly.

sorry..actually i have this one

$val1=explode(";",$_GET['val1']);

$countval2=count($val1);

$val2=explode(";",$_GET['val2']);

$countval2=count($val2);

$value=array_diff($val1,$val2);

 

n i wish to put the difference result in a string called $choice

 

 

 

Have you ever read up on coding practices? Read up here. It's only three pages, and everyone who has to read your code will love you for it.

 

Now, back to your question.

 

What I have so far for you is,

$val1=explode(";",$_GET['val1']);
$countval2=count($val1);
$val2=explode(";",$_GET['val2']);
$countval2=count($val2);
$value=array_diff($val1,$val2);

foreach ($value as $val) {
   $choice="";
   for ($i=0; $i<count($val); $i++) {
      $choice=$choice.$val[$i].";";
   }

   echo $choice;
}

 

After coding standards, I have changed it to look like this:

$val1      = explode(";",$_GET['val1']);
// This next line has no use right now
$countVal1 = count($val1);
$val2      = explode(";",$_GET['val2']);
// This next line has no use right now
$countVal2 = count($val2);
$value     = array_diff($val1 ,$val2);

foreach ($value as $val) {
   $choice="";
   for ($i=0; $i<count($val); $i++) {
      $choice=$choice.$val[$i].";";
   }

   echo $choice;
}

 

Now, other than that, I am very confused about what you want versus what you have. Please describe what you want in a little bit more detail.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.