Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 714
Handsome Nerd Avatar asked Dec 20 '22 07:12

Handsome Nerd


1 Answers

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);
    }
}
like image 121
Baba Avatar answered Jan 01 '23 19:01

Baba