1

I'm creating a Wordpress Plugin which uses a jQuery script. I've created a PHP array which contains its options like:

$settings = array('setting1' => 'value1', 'setting2' => 'value2', 'setting3' => 10)

I was now going to use foreach to loop over the items and print them like this:

foreach($settings as $setting => $value) {

if (is_string($value)) { $value = "'" . $value . "'"; }
$output .= $setting . ':' . $value .',';

}

which should make me end up with:

(window).load(function() {
$('#widget').myWidget({
    setting1:'value1', 
    setting2:'value2', 
    setting3:10})

With the current setup I end up with the last entry having a ',' at the end (one too many) which means I get a Javascript error, so I need to remove it.

All with all, I have the feeling I'm doing something very dirty (including the is_string check) and I was wondering if there is a neat way to deal with this?

4 Answers 4

2

There is a json_encode function if you're using PHP >= 5.2

Sign up to request clarification or add additional context in comments.

Comments

2

You should use json_encode() for this. It does all the dirty work for you.

(window).load(function() {
    $('#widget').myWidget(
        <?php echo json_encode($settings); ?>
    );
}

2 Comments

Excellent, I never imagined it would be so easy. Thanks a lot!
Yeah, the JSON support is really nice.. And btw., it works in both directions (json_decode()) :).
1

Have you tried json_encode ?

Exemple from the docs:

<?php
$arr = array ('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5);

echo json_encode($arr);
?> 

Would output

{"a":1,"b":2,"c":3,"d":4,"e":5}

Comments

1

Here's a little thing I like to use when dealing with situations like this. I know it doesn't really answer your question, but it is an elegant way of solving the comma problem.

$comma = '';
foreach($settings as $setting => $value) {
  if (is_string($value)) { 
    $value = "'" . $value . "'";
    $output .= $comma . $setting . ':' . $value;
    $comma = ',';
  }
}

So on the first run $comma is blank, but after that it gets put between every new entry.

3 Comments

No -1 because this solution works, but definitely not a good one.
Could you enlighten me as to why this is not a good solution. Perhaps my code is suffering for it...
Because an existing function, json_encode, already do the work. Odds are that this function will be maintained longer that your personnal code and by smarter people that you and me.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.