1

I have one string in mysql database that contains characters and would like to do it next:

$string = "actor1 as aaa, actor2 as bbb, actor3 as ccc";

for (do a loop for 0 to length of the $string) {
   echo actor1
   echo aaa
}

So loop goes and print each time:

actor1
aaa

actor2
bbb

actor3
ccc

How to do that in PHP?

1
  • 1
    You better use explode. Commented Jan 11, 2013 at 13:58

3 Answers 3

6

Try with:

$string = "actor1 as aaa, actor2 as bbb, actor3 as ccc";
$groups = explode(',', $string);

foreach ( $groups as $group ) {
  $items = explode(' as ', trim($group));
  foreach ( $items as $item ) {
    echo $item . '<br/>';
  }
  echo '<br/>';
}

or improoved without second loop:

foreach ( $groups as $group ) {
  list($actor, $role) = explode(' as ', trim($group))
  echo $actor . '<br/>';
  echo $role . '<br/>';
  echo '<br/>';
}
Sign up to request clarification or add additional context in comments.

Comments

4
foreach(explode(",", $string) as $value) {
    $parts = explode(" as ", $value);
    echo trim($parts[0])."<br/>".trim($parts[1])."<br/>";        
}

1 Comment

Thanks..all..:) I try and use solution by periklis and is doing very nice...Thank You.
0

NB: I've assumed you have a query but just haven't put in appropriate query strings, so I've added a typical mySQL example.

$query = mysql_query("SELECT actor1 as aaa, actor2 as bbb, actor3 as ccc FROM some_table");
$result = mysql_fetch_object($query);
$numrows = mysql_num_rows($query);

for ($i = 1; $i <= $numrows; $i++) {
  echo "actor1 <br>";
  echo $result->aaa . "<br>";
  echo "actor3 <br>";
  echo $result->bbb . "<br>";
  echo "actor3 <br>";
  echo $result->ccc . "<br>";
}

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.