Question

I looking for a way (regex, snippet ,plugin etc) to convert the old arrays with the new php syntax with sublimeText.

// Old synthax
$var = array(
   'foo' => 'bar' 
);

// New synthax
$var = [
   'foo' => 'bar'
];

someone has an idea ?

Was it helpful?

Solution

I found a script that does the job perfectly !

https://github.com/thomasbachem/php-short-array-syntax-converter

OTHER TIPS

I found out that it is also possible to do this with the php codesniffer: https://github.com/squizlabs/PHP_CodeSniffer

phpcbf src/ --standard=Generic --sniffs=Generic.Arrays.DisallowLongArraySyntax

In this example you have to replace src/ with the folder containing the scripts. Alternatively you can provide a file name.

Maybe a bit late, but I created my own. Maybe not pretty, but it does do the job I want. If you do not like tab, change \t in indent function to 2 or 4 spaces.

    function loopArray(array $array, $loopcount = 0) {

        $returnString = ($loopcount == 0) ? "[\n" : "";

        $tabKey = indent($loopcount + 2);
        $tabValue = indent($loopcount + 3);

        $lastKey = array_key_last($array);

        foreach ($array as $key => $value) {

            $totalChildren = count($array[$key]);

            $returnString .= $tabKey . '"' . $key . '" => ';

            if ($totalChildren == 0) $returnString .= '[]';
            if ($totalChildren > 0 && is_array($array[$key])) $returnString .= '[' . "\n";

            if (is_array($value)) {

                $returnString .= loopArray($value, $loopcount + 1);
            } else {

                if ($totalChildren == 1) $returnString .=  '"' . $value . '"';
                if ($totalChildren > 1)  $returnString .=  $tabValue . '"' . $value . '"'  . ",\n";
            }

            $returnString .= ($lastKey == $key) ? "\n" . indent($loopcount+1) . "]" : ",\n";
        }

        return $returnString;
    }

    function indent($ammount) {

        return str_repeat("\t", $ammount);
    }

/** use function below only prior to php 7.3 */

    function array_key_last(array $array) {

        $key = NULL;

        if ( is_array( $array ) ) {

            end( $array );
            $key = key( $array );
        }

        return $key;
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top