I'm setting up a sports league website and I am using this code below to pull the names of all the teams from a single file, but I have to pull the team names in multiple places, on multiple pages, so have come to this solution. There will be 10-20 teams, but here's an example of what I'm doing, with just 5:
<?php echo ($team = file('teams.php', FILE_IGNORE_NEW_LINES))? $team[1] : 'Unable to read file'; ?>
<?php echo ($team = file('teams.php', FILE_IGNORE_NEW_LINES))? $team[2] : 'Unable to read file'; ?>
<?php echo ($team = file('teams.php', FILE_IGNORE_NEW_LINES))? $team[3] : 'Unable to read file'; ?>
<?php echo ($team = file('teams.php', FILE_IGNORE_NEW_LINES))? $team[4] : 'Unable to read file'; ?>
<?php echo ($team = file('teams.php', FILE_IGNORE_NEW_LINES))? $team[5] : 'Unable to read file'; ?>
The teams.php file is just a simple list of team names, with line 1 blank or "---" so that the numbering can start at 1 instead of 0:
---
Team Name 1
Team Name 2
Team Name 3
Team Name 4
Team Name 5
I'm wondering if I can just set the $team
variable once (at the top of each page, in a header.php file that is included in all the pages) and then just do a simpler call/include for each team name, something like this?:
header.php:
<?php $team = file('teams.php');?>
standings.php:
<?php $team[1];?>
<?php $team[2];?>
<?php $team[3];?>
<?php $team[4];?>
<?php $team[5];?>
Or maybe there's a completely different/better/simpler way of doing this.
I ended up going with a simple array:
<?php
$team = array(
'01' => 'Team 01 Name',
'02' => 'Team 02 Name',
'03' => 'Team 03 Name',
'04' => 'Team 04 Name',
'05' => 'Team 05 Name'
);
?>
So I can then call the teams where needed on multiple pages, ie:
<?php echo $team['01']?>
Have you heard PHP has loops - see http://www.php.net/manual/en/control-structures.for.php
<?php
if (false!==$file=file('./teams.php', FILE_IGNORE_NEW_LINES))
for ($x=0;5<$x;++$x)
echo $file[$x];
else
echo 'Unable to read file';