Strings as arrays

arrays, php, string, syntax

Solution

`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);
    }
}

Problem

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.

Original source