Convert php arrays with the new syntax
Asked Answered
P

3

5

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 ?

Personify answered 3/6, 2014 at 14:31 Comment(3)
@Personify You should change your edit into an answer and accept it.Gurley
I don't think new users can accept their own answers yet can they?Newark
Yes i can, but in two days :)Personify
P
6

I found a script that does the job perfectly !

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

Personify answered 3/6, 2014 at 21:10 Comment(0)
W
5

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.

Wailoo answered 27/8, 2018 at 10:36 Comment(1)
If you use PhpStorm, It will automatically convert it to new format if the rule is given in the configuration file.Rudich
E
0

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($amount) {

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

/** 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;
    }
Ecdysiast answered 14/1, 2019 at 6:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.