Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

SarahS's avatar
Level 12

Pass a PHP Array to AlpineJS x-data

I have a PHP array $authors->books and I want to pass into this x-data instead of the [1,2,3,4,5], how do I do that?

x-data="{ feed: [1,2,3,4,5] }"
0 likes
11 replies
tykus's avatar

You can use the @json directive:

x-data="{ feed: @json([1,2,3,4,5]) }"
SarahS's avatar
Level 12

@tykus OK so I've tried this:

x-data="{ feed: @json($authors->books)}"

but that doesn't work. How should I write it?

SarahS's avatar
Level 12

@tykus It's giving me the key and and the value. How do I get just the value?

tykus's avatar

@SarahS74 what do you mean? What does $authors->books data actually look like?

SarahS's avatar
Level 12

@tykus

<div class="m-4" x-data="{
            feed: {" 1":1000,"2":1001,"3":1002,"4":1003,"5":1004},="" dragging:="" null,="" dropping:="" timer:="" null}"="" @drop.prevent="if(dragging !== null &amp;&amp; dropping !== null){if(dragging < dropping) feed = [...feed.slice(0, dragging), ...feed.slice(dragging + 1, dropping + 1), feed[dragging], ...feed.slice(dropping + 1)]; else feed = [...feed.slice(0, dropping), feed[dragging], ...feed.slice(dropping, dragging), ...feed.slice(dragging + 1)]}; dropping = null;" @dragover.prevent="$event.dataTransfer.dropEffect = &quot;move&quot;">
tykus's avatar
tykus
Best Answer
Level 104

@SarahS74 you have an associative array for $authors->books;

What you want is an array of the keys only???

x-data="{ feed: @json(array_keys($authors->books))}"

or the values only???

x-data="{ feed: @json(array_values($authors->books))}"
1 like
SarahS's avatar
Level 12

@tykus The array_values is perfect thank you. Can I ask, why do we need the @json directive?

tykus's avatar

why do we need the @json directive?

@SarahS74 try to echo an array; you'll get an error

{{ array_values($authors->books) }}
SarahS's avatar
Level 12

@tykus OK so basically to get a PHP array to work with Javascript we need to convert it to JSON first.

tykus's avatar

@SarahS74 exactly. A numeric (beginning at 0) indexed array will become a JSON array; whereas an associative (keyed) array will become a JSON Object.

Please or to participate in this conversation.