snipt

Ctrl+h for KB shortcuts
Sign up for : store and share your own code snippets.
#136258

JavaScript

Convert php array to Javascript array

1
2
3
4
5
6
<?php
$php_array = array('abc','def','ghi');
$js_array = json_encode($php_array);
echo "var javascript_array = ". $js_array . ";\n";
?>
console.log( javascript_array );
https://snipt.net/embed/e51096dfe7d0911468f6ef93246883b4/
https://snipt.net/raw/e51096dfe7d0911468f6ef93246883b4/
e51096dfe7d0911468f6ef93246883b4
js
JavaScript
6
2015-04-18T01:18:38
True
True
Aug 26, 2014 at 11:32 PM
/api/public/snipt/136258/
convert-php-array-to-javascript-array-b05e6202
<table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre><a href="#L-1">1</a> <a href="#L-2">2</a> <a href="#L-3">3</a> <a href="#L-4">4</a> <a href="#L-5">5</a> <a href="#L-6">6</a></pre></div></td><td class="code"><div class="highlight"><pre><span id="L-1"><a name="L-1"></a><span class="o">&lt;?</span><span class="nx">php</span> </span><span id="L-2"><a name="L-2"></a><span class="nx">$php_array</span> <span class="o">=</span> <span class="nx">array</span><span class="p">(</span><span class="s1">&#39;abc&#39;</span><span class="p">,</span><span class="s1">&#39;def&#39;</span><span class="p">,</span><span class="s1">&#39;ghi&#39;</span><span class="p">);</span> </span><span id="L-3"><a name="L-3"></a><span class="nx">$js_array</span> <span class="o">=</span> <span class="nx">json_encode</span><span class="p">(</span><span class="nx">$php_array</span><span class="p">);</span> </span><span id="L-4"><a name="L-4"></a><span class="nx">echo</span> <span class="s2">&quot;var javascript_array = &quot;</span><span class="p">.</span> <span class="nx">$js_array</span> <span class="p">.</span> <span class="s2">&quot;;\n&quot;</span><span class="p">;</span> </span><span id="L-5"><a name="L-5"></a><span class="o">?&gt;</span> </span><span id="L-6"><a name="L-6"></a><span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span> <span class="nx">javascript_array</span> <span class="p">);</span> </span></pre></div> </td></tr></table>
array, convert, javascript, php
Copyrighted, illegal, or inappropriate content? Email nick@snipt.net.