<p>If I'm following you, arrays are 0-indexed, so this would work (with a bit of cleanup).</p>

<pre><code>{% set names = 'first-last'|split('-') %}
{% set firstNameSlug = names[0] %}
{% set lastNameSlug = names[1] %}

{{ firstNameSlug }}
{{ lastNameSlug }}
</code></pre>

CC BY-SA 4.0
2020-03-13T21:49:52.570Z
2020-03-13T21:49:52.570Z
Brad Bell
<p>I want to split my variable into two new variables before and after the dash character "-".</p>

<p>How do I adjust my code below to enable this to happen?</p>

<pre><code>{% set name = 'first-last' %}
{% set firstNameSlug = name|split('-')[1] %}
{% set lastNameSlug = name|split('-')[2] %}

{{ firstNameSlug }}
{{ lastNameSlug }}
</code></pre>

<templating>
Splitting a Twig Variable into 2 Variables
# Splitting a Twig Variable into 2 Variables

(Asked by: username_0 on 2020-03-13)

I want to split my variable into two new variables before and after the dash character "-".
How do I adjust my code below to enable this to happen?
{% set name = 'first-last' %}
{% set firstNameSlug = name|split('-')[1] %}
{% set lastNameSlug = name|split('-')[2] %}

{{ firstNameSlug }}
{{ lastNameSlug }}

**Tags:** templating

---

## 1 answers

### Answer by username_1 on 2020-03-13. Score: 2 | Accepted answer

If I'm following you, arrays are 0-indexed, so this would work (with a bit of cleanup).
{% set names = 'first-last'|split('-') %}
{% set firstNameSlug = names[0] %}
{% set lastNameSlug = names[1] %}

{{ firstNameSlug }}
{{ lastNameSlug }}


---

