I have multiple arrays containing mathml(xml) elements.
For example my arraylist:
Array
(
[0] => <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] => <mi>x</mi><mo>+</mo><mn>2</mn><mo>=</mo><mn>3</mn>
[2] => <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>
)
I want all array to start with <mo>
but if it starts with <mo>
then it's fine like array [3].
For example the expected output I want
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>
)
As you can see all array starts with <mo>
.
Below is my current code to add it:
$ress = array();
$arr_result=[];
for ($i=0; $i <= $length ; $i++) {
$ress=$result[$i];
if ($pos = (substr($ress,0,3)!="<mo>")) {
$arr_result[]=array_unshift($ress, "<mo>+</mo>");
}
else{
$arr_result[]=$ress;
}
}
print_r($arr_result);
$result store the array.
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>
)