Real Dreams
Real Dreams

Reputation: 18010

Strings as arrays

In PHP the following is valid:

$n='abc';
echo $n[1];

But it seems that the following 'abc'[1]; is not.

Is there anything wrong with its parser?

Unfortunately currently even $n[1] syntax is not so useful ◕︵◕ , because it does not support Unicode and returns bytes instead of letters.

Upvotes: 4

Views: 92

Answers (3)

Baba
Baba

Reputation: 95121

echo 'abc'[1]; is only valid in PHP 5.5 see Full RFC but $n[1] or $n{2} is valid in all versions of PHP

See Live Test

Unfortunately currently even $n[1] syntax is not so useful ◕︵◕ , because it does not support Unicode and returns bytes instead of letters.

Why not just create yours ?? Example :

$str = "Büyük";
echo $str[1], PHP_EOL;

$s = new StringArray($str);
echo $s[1], PHP_EOL;

// or

echo new StringArray($str, 1, 1), PHP_EOL;

Output

�
ü
ü

class Used

class StringArray implements ArrayAccess {
    private $slice = array();

    public function __construct($str, $start = null, $length = null) {
        $this->slice = preg_split("//u", $str, - 1, PREG_SPLIT_NO_EMPTY);
        $this->slice = array_slice($this->slice, (int) $start, (int) $length ?  : count($this->slice));
    }

    public function slice($start = null, $length = null) {
        $this->slice = array_slice($this->string, (int) $start, (int) $length);
        return $this ;
    }

    public function offsetSet($offset, $value) {
        if (is_null($offset)) {
            $this->slice[] = $value;
        } else {
            $this->slice[$offset] = $value;
        }
    }

    public function offsetExists($offset) {
        return isset($this->slice[$offset]);
    }

    public function offsetUnset($offset) {
        unset($this->slice[$offset]);
    }

    public function offsetGet($offset) {
        return isset($this->slice[$offset]) ? $this->slice[$offset] : null;
    }

    function __toString() {
        return implode($this->slice);
    }
}

Upvotes: 10

silkfire
silkfire

Reputation: 25965

The literal string access syntax 'abc'[1] is very much valid in JavaScript, but won't be supported in PHP until version 5.5.

Upvotes: 0

Jeff Cashion PhD
Jeff Cashion PhD

Reputation: 674

No, this is proper operation. To do what you are trying to, you could try:

echo substr('abc', 1, 1);

Upvotes: 1

Related Questions