[Solved] How to add xml child to first index of an array using php


There are a lot if issues with the code you have, so I’ve just written something new…

$result = ["<mo>+</mo><mi>x</mi><mo>=</mo><mfrac><mrow><mo>-</mo><mi>b</mi><mo>±</mo><msqrt><msup><mi>b</mi><mn>2</mn></msup><mo>-</mo><mn>4</mn><mi>a</mi><mi>c</mi></msqrt></mrow><mrow><mn>2</mn><mi>a</mi></mrow></mfrac>",
    "<mo>+</mo><mi>x</mi><mo>+</mo><mn>2</mn><mo>=</mo><mn>3</mn>",
    "<mfrac><mrow><mn>2</mn><mi>x</mi><mo>+</mo><mn>2</mn></mrow><mn>3</mn></mfrac><mo>-</mo><mn>3</mn><mo>=</mo><mn>2</mn>",
    "<mo>-</mo><mn>3</mn><mo>+</mo><mn>2</mn><mo>=</mo><mi>x</mi>"
    ];
$arr_result=[];

for ($i=0; $i < count($result) ; $i++) {
    if (substr($result[$i],0,4)!="<mo>") {
        $arr_result[]= "<mo>+</mo>".$result[$i];
    }
    else    {
        $arr_result[]= $result[$i];
    }

}
print_r($arr_result);

This just goes through each line at a time, checking the first 4 chars for <mo> and adds them into the new value if it’s not there.

Output is…

Array
(
    [0] => <mo>+</mo><mi>x</mi><mo>=</mo><mfrac><mrow><mo>-</mo><mi>b</mi><mo>±</mo><msqrt><msup><mi>b</mi><mn>2</mn></msup><mo>-</mo><mn>4</mn><mi>a</mi><mi>c</mi></msqrt></mrow><mrow><mn>2</mn><mi>a</mi></mrow></mfrac>
    [1] => <mo>+</mo><mi>x</mi><mo>+</mo><mn>2</mn><mo>=</mo><mn>3</mn>
    [2] => <mo>+</mo><mfrac><mrow><mn>2</mn><mi>x</mi><mo>+</mo><mn>2</mn></mrow><mn>3</mn></mfrac><mo>-</mo><mn>3</mn><mo>=</mo><mn>2</mn>
    [3] => <mo>-</mo><mn>3</mn><mo>+</mo><mn>2</mn><mo>=</mo><mi>x</mi>
)

0

solved How to add xml child to first index of an array using php