Thread: Array index syntax
thedarkness

Just came across the following syntax and wondered what was the difference is, if any, between this;

$keyboard[$word{$i}]

and this;

$keyboard[$word[$i]]

?

Cheers,
td

Bompa

I'm out of my language, but in

perl

  I would say the first is a hash element
and the second is an array element.


Bompa

perkiset

Did that actually work?

The curlybraces are for surrounding a variable name while dereferencing in a string... I've never seen that notation and I speculate that it is an error... but I'm dying to know if it worked and if so, what it did...

/p

perkiset

And BTW -

quote author=thedarkness link=topic=102.msg482#msg482 date=1177494090

$keyboard[$word[$i]]


... is not actually a multi-dim array at all... its just evaluating the $word array value before evaluating the $keyboard value... multidim would look like this: $keyboard[$x][$y][$z]

/p

thedarkness

Of course, doh!

Perk: PM'ed you some code.

Cheers,
td

tobsn

thats for strings


$string = '1234567890';
for( $i = 0; $i < strlen( $string ); $i++ ) {
    echo $string{$i};
}


or it is for generating strings like $i = 1; echo $string{$i}; echo $string1; ||  $i = 'a'; echo $string{$i}; echo $stringa;

cant remember for what it was... one of the examples above  Applause

perkiset

simple strings can be referenced with the normal array syntax - that's the only way I've ever done it:

$myStr = 'Hello World';
print $myStr[1]; // prints 'e'

... was this an older

PHP

  syntax?

m0nkeymafia

td:

I think strings are stored as a character array, so $charArray[$i] will return the character at that index.

perkiset

They are... the only caveat is that this is a read only feature... unlike C you cannot write to those array positions.

Which is a drag, really...

/p

m0nkeymafia

Didnt know that perk, bet that caused a few people a few headaches in the past

thedarkness

quote author=m0nkeymafia link=topic=102.msg1795#msg1795 date=1180297463

td:

I think strings are stored as a character array, so $charArray[$i] will return the character at that index.


Yeah, I truly grok this dude. The OP was about the use of the unusual syntax, not "Can anyone teahc me how to use character arrays?"  Applause

Cheers,
td

perkiset

quote author=m0nkeymafia link=topic=102.msg1806#msg1806 date=1180368016

Didnt know that perk, bet that caused a few people a few headaches in the past


Quick headache, since it is painfully obvious you can't write to the array (it'll bomb at run time) but an enormous tease... it looks SO CLOSE with the read syntax... pissed me off. I'd love direct access to that memory but doing so would open a can of worms as huge as C++ itself. The next thing you know it's pointers to pointers and self-managed garbage collection. Ah well... cest la vie...

/p


Perkiset's Place Home   Politics @ Perkiset's