Friday, February 10, 2012

How can I add a variable to an array?


How can I add a variable to an array? Let say I have variable named $new_values :




$new_values=",543,432,888"



And now I would like to add $new_values to function. I tried in that way:




phpfunction1(array(114,763 .$new_values. ), $test);



but I got an error Parse error: syntax error, unexpected T_VARIABLE, expecting ')'



How my code should look if I would like to have array(114,763,543,432,888) ?

6 comments:

  1. $new_values=",543,432,888";


    should be converted to an array:

    $new_values= explode(',', "543,432,888");


    and merged to existing values with:

    array_merge(array(114,763), $new_values);


    Whole code should looks like:

    $new_values = explode(',', "543,432,888");
    $values = array(114,763);
    $values = array_merge($values, $new_values);
    phpfunction1($values, $test);


    If you pass to explode a string that is starting with , you will get first empty element, so avoid it.

    ReplyDelete
  2. if you have an array already i.e.

    $values = array(543,432,888);


    You can add to them by : $values[]=114; $values[]=763;

    Apologies if I missed the point there...

    ReplyDelete
  3. In your example, $new_values is a string, but, since it's comma delimited, you can create an array directly from it. Use $new_array = explode(',', $new_values); to create an array from the string.

    ReplyDelete
  4. You need to convert the string into an array using the explode function and then use the array_merge function to merge the two arrays into one:

    $new_values=",543,432,888";

    $currentArray=array(114,763);

    $newArray=array_merge($currentArray,explode(',',$new_values));

    functionX($newArray...)


    But watch out for the empty array element because of the first comma.
    For that use "trim($new_values, ',')" - see answer from rajesh.

    ReplyDelete
  5. you can do like this.

    $old_values = array(122,555);
    $new_values=",543,432,888";
    $values = explode(',', trim($new_values, ','));
    $result = array_merge($old_values, $values);
    print_r($result);

    ReplyDelete
  6. try array merge

    looks like this

    phpfunction1(array_merge(array(114,763) ,$new_values), $test);

    and yes your first array is not an array
    change it to this

    $new_values=Array(543,432,888);

    ReplyDelete