Jump to content

$string containing code


Michan

Recommended Posts

Hi there,

I'm trying to create a $string to bring up multiple times later. It contains code, and I can't figure out how to do it.

The string is:

[code]$string {

echo ('|');

for($i = 0; $i < sizeof($game); $i++)
{
echo ($game[$i].'|');
}

echo ('|');

}[/code]

Is there a special way to do this for strings that are more than just text that needs reproducing?

Many thanks,
- Mi
Link to comment
https://forums.phpfreaks.com/topic/30392-string-containing-code/
Share on other sites

craygo there's really no reason to initialize as an empty string just to turn around and append a '|' character to it. Also you'll end up with two '|'s at the end the way you wrote it (which may or may not be the way you intended it...it just didn't seem likely that you would want it that way).

[code]<?php
$string = "|";
for ($i = 0, $game_size = sizeof($game); $i < $game_size; $i++) $string .= $game[$i] . "|";
echo $string;
?>[/code]

Setting $game's size to a temporary variable instead of checking $i vs sizeof($game) each loop will speed up your script significantly. Also you don't [i]need[/i] to use braces {} unless you have more than one statement.

However it appears to me that what Michan is [i]wanting[/i] to do is create a function like this:

[code]<?php
function print_game() {
  $game_size = sizeof($game);
  if (!$game_size) return false;
  $string = "|";
  for ($i = 0; $i < $game_size; $i++) $string .= $game[$i] . "|";
  echo $string;
  return $string;
  }
?>[/code]

Then you can call [color=green]print_game()[/color] in your script and it will echo $game's contents to the screen as well as returning the string that was printed, or false if $game hasn't been set yet.
[quote author=craygo link=topic=118349.msg483538#msg483538 date=1165953987]
I didn't write it he did. If he wants 2 "|" at the end up to him. I just gave him something to start with. Figured if it was going to contain code somewhere on his page might start it off blank. But whatever.

Ray
[/quote]

I noticed that so I tried to clarify that you [i]both[/i] put two '|'s at the end which I suspected wasn't how he wanted. ;)

I'm glad we were able to help you sort this out Michan! :)

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.