Replacing string with a variable in php

I have following code in my plugin of WordPress:

wp_localize_script('ffd_js_script', 'myAjax', array(
            'ajaxurl' => admin_url('admin-ajax.php'),
            'idinfo' => $myoptionValue[idinfo],
            'index1' => $myoptionValue[id1],
            'index2' => $myoptionValue[id2]
            )
        );

I want to replace

'index1' => $myoptionValue[id1],
'index2' => $myoptionValue[id2]

with

for($i=1; $i<= $myoptionValue[fieldcount]; $i++)
        {
            $arguments .= ',"index"'.$i.'=>'.$myoptionValue[id.$i];
        }

So that I have

        wp_localize_script('ffd_js_script', 'myAjax', array(
            'ajaxurl' => admin_url('admin-ajax.php'),
            'idinfo' => $myoptionValue[idinfo]
            $arguments
            )
        );

Apparently I’m thinking it might be as simple as this, but it isn’t, where is my mistake?

EDIT:

full code:

require( plugin_dir_path( __FILE__ ) . 'menu.php');
require_once( plugin_dir_path( __FILE__ ) . 'getuser.php');

add_action( 'wp_enqueue_scripts', 'ffd_load_scripts' );

function ffd_load_scripts()
{
$myoption =  get_option( 'fixformdata_options' );
$myoptionValue = maybe_unserialize( $myoption );  

$arguments = array();
for($i=1; $i<= $myoptionValue[fieldcount]; $i++)
{
    $arguments['index'.$i] = $myoptionValue['id'.$i];
}

wp_register_script('ffd_js_script', WP_PLUGIN_URL.'/FixFormData/js/ffd_js_script.js', array('jquery'));
wp_localize_script('ffd_js_script', 'myAjax', merge_array(array(
    'ajaxurl' => admin_url('admin-ajax.php'),
    'idinfo' => $myoptionValue['idinfo']),$arguments)
    );

wp_enqueue_script('jquery');
wp_enqueue_script('ffd_js_script', plugin_dir_url(__FILE__) . 'js/ffd_js_script.js');

}

1 Answer
1

There are 4 valid ways of defining a string, see this question for more details.

However in your case there is a special exception provided by PHP. Most users are unaware of it however, and it does leave ambiguities, as it’s no longer possible to tell a string literal, a constant, or a define apart, making it very difficult for other programmers to read your code ( e.g. yourself in 9 months time ).

So your code:

for($i=1; $i<= $myoptionValue[fieldcount]; $i++)
{
    $arguments .= ',"index"'.$i.'=>'.$myoptionValue[id.$i];
}

Is trying to append a string to the end of an array, which doesn’t work. Arrays aren’t strings, and you can only use the .= and . operators on strings. Also $myoptionValue[id.$i] violates the special case situation as the expression is now ambiguous ( does it mean ‘id.$i’, ‘id’.$i, or “id.$i”? )

To add an item to an array you need to do one of the following:

$arr = array();
$arr['key'] = 'value';
$arr[] = 'value without a key';
array_push( $arr, 'value1', 'value2', 'value3', etc... );

So your loop should be:

for ( $i=1; $i <= $myoptionValue['fieldcount']; $i++ ) {
    $arguments['index'.$i] = $myoptionValue['id'.$i ];
}

Leave a Comment