1

I have a php code that looks into an xml array; what I want to do is change the next value of that find. I can echo the output correctly, but when trying to change the value I get an fatal error.

I call my function this way:
$xml = replaceDeleteOrAddMethod("void", "method", "put", $templateID_category, $xml, "category", "itsastring");

and the function I made looks like this:

function replaceDeleteOrAddMethod($element, $methodName, $methodValue, $newValue, $xml, $methodstringname, $methodvartype)
{
    //echo "replacing Value for: " .  $propertyValue;
  foreach ($xml->xpath("//" . $element) as $tmp)
  {
    //echo $tmp->string . "<br>"; 
    if((string) $tmp[$methodName] == $methodValue )
    {
        if ($tmp->string == $methodstringname)
        {
            switch ($methodvartype){
                case "itsastring":
                    echo $tmp->string . "<br>";
                    echo next($tmp->string) . "-> NewValue: " . $newValue . "<br>";
                    next($tmp->string) = $newValue;
                break;
                case "itsaint":
                    echo $tmp->int . "<br>"; 
                    next($tmp->int) = $newValue;
                break;
                case "itsabool":
                    echo $tmp->bool . "<br>"; 
                    next($tmp->bool) = $newValue;
                break;
            }
        }
    }
  }
  return($xml);

}

If I do $tmp->string = $newValue I am able to edit the string with the new value; but next($tmp->string) = $newValue; gives me a fatal error.

Thanks for the help.

JSChasle
  • 45
  • 8
  • possible duplicate of [PHP - Modify current object in foreach loop](http://stackoverflow.com/questions/10121483/php-modify-current-object-in-foreach-loop) – River Aug 03 '15 at 23:40
  • it's not the same, I am not talking about referencing using & I am talking why using next does not allow me to change a value, but echoing that next vlaue works – JSChasle Aug 04 '15 at 00:42
  • Just needed to do: $tmp->string[1] = $newValue; (to get my second string value – JSChasle Aug 05 '15 at 04:09

1 Answers1

1

A value cannot be assigned to (in PHP, or any programming language for mortals).

Here's a simplified example:

$ints = array(1, 2, 3, 4, 5);
$first = current($ints);      // $first = 1;
next($ints) = 99;             // 2 = 99;

This doesn't make sense. next($ints) in this context returns 2. It cannot be assigned to 99.


It's not clear whether $tmp->string (or its siblings in your code snippet) are arrays. next will only have the desired behavior when operating on an array.

Assuming what you want to do is operate on the next element in your XPath loop, you can instead create a trigger variable (e.g., $matched = false;). On a "match" set it equal to true, and then on the next iteration, check if($matched == true); if it does, then replace the current value with $newValue.

Jacob Budin
  • 9,753
  • 4
  • 32
  • 35