---
title: Sorting parameter arguments and array keys in Vim
date: 2024-09-03 19:03:27
tags: [PHP, Vim, Software Development]
---

Given this PHP code (for example):

```php
$a = [
  'b' => 2,
  'a' => 4,
  'k' => 5,
  'f' => 1,
  'd' => 3,
];

$b = new Foo(
  b: 2,
  a: 4,
  k: 5,
  f: 1,
  d: 3,
);
```

You can use `vi(` and `vi[` to visually select the text within the array or parentheses, and then ":sort" to sort the text within the selected range.

Using `vi(` and `vi[` instead of `vi)` and `vi]` excludes the lines that around the text to sort.

After running these commands, you should get this:

```php
$a = [
  'a' => 4,
  'b' => 2,
  'd' => 3,
  'f' => 1,
  'k' => 5,
];

$b = new Foo(
  a: 4,
  b: 2,
  d: 3,
  f: 1,
  k: 5,
);
```

At some point, I'll look into saving this as a macro with a keymap like `<leader>sa` (sort arguments) and `<leader>sk` (sort keys).