1

I am creating a website and I need to to some PHP in my jQuery.

My code is as follows;

notifications.initMenu({
    2:'#chatPage #tabs #2',
    3:'#chatPage #tabs #3',
    4:'#chatPage #tabs #4',
    5:'#chatPage #tabs #5'
});

I want it so that it uses a while loop to echo;

$pageID:'#chatPage #tabs #$pageID',

And then on the last record echo;

$pageID:'#chatPage #tabs #$pageID'

Any ideas? Thanks.

genesis
  • 50,477
  • 20
  • 96
  • 125
oyed
  • 572
  • 2
  • 14
  • 34

2 Answers2

7
$array = array();
while( ....) {
    $array[] = "\n  $pageID:'#chatPage #tabs #$pageID'";
}
echo implode(',', $array);
Karoly Horvath
  • 94,607
  • 11
  • 117
  • 176
  • just for curiosity, which one is faster, $array[] or array_push()? – Simon Jul 24 '11 at 19:28
  • 1
    @Simon: Obviously [`$array[]`](http://stackoverflow.com/questions/1074059/array-push-vs-array-which-is-fastest). – Shef Jul 24 '11 at 19:32
  • @Simon: According to a test conducted at the following page (http://stackoverflow.com/questions/559844/whats-better-to-use-in-php-array-value-or-array-pusharray-value), assigning variables using $array[] seems to be up to 50% faster than using array_push(). – karllindmark Jul 24 '11 at 19:33
  • the manual also mentions that it's faster for one element, which is a bit weird because a good compiler could very easily detect that it's just one element passed and emit the same bytecode, but oh well, php... anyway, this is tipically below the level of the optimisation that you have to worry about – Karoly Horvath Jul 24 '11 at 19:38
1

If the comma is what you ask about:

for ($i = 2; $i <= 5; $i++) {
    echo "$i:'#chatPage #tabs #$i'" . ($i !== 5 ? "," ? "") . "\n";
}
Mikulas Dite
  • 7,790
  • 9
  • 59
  • 99