4

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.

3 Answers 3

10

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);
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

It also explicitly states this in the documentation: php.net/manual/en/language.types.string.php
1

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

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.