Actually you are right, I am so blur today, I forgot that there is not a need to increase the array dimension, because the array dimension will be automatically increased when I insert array into the array. It takes a bit of writing but here is exactly what I am trying to do , maybe you can help me to improve, I am trying to make an algebra calculator , such as if I had an equation
$str = '4 + r - 5 = 8';
it should give the result of "r" as 9, I have done this by inputing each character into $segment array in this way;
$segment = array();
for($i=0; $i < strlen($str); $i++)
$segment[$i] = $str[$i];
Then I moved all the numbers at the left hand side to the right hand side which is after the equal operator and also change the number sign from positive to negative and vice versa. The number that has been moved to the right hand side is stored by appending into the $segment array.
The equation will look like this now which is stored in the $segment array.
4 + r - 5 = 8 - 4 + 5;
$rhs = '';
for($j=$equalSignIndex+1; $i< sizeof($segment); $i++){
$rhs =. $segment[$i]; // Get the right hand side numbers which is 8- 4 + 5
}
return eval("return $rhs;"); // gives the result of 9
The above one might have better way of doing it. But what I am having a problem which is the parentheses, such as below
((2 + 1) * t ) + 5 = 8;
I was thinking to store the character in parentheses into $segment array in multi dimension like
$segment[0] = '((2 + 1) * t )';
$segment[0][0] = '(2 + 1)';
$segment[0][1] = '*';
$segment[0][2] = 't';
$segment[1] = '+' // We have come out from parentheses so we want to store in new index
$segment[2] = '5';
$segment[3] = '=';
$segment[4] = '8';
The use of multi dimension array for me is to let me be able to keep track of the position inside the parentheses.So that I know the very first thing to do is to evaluate those from the innermost parentheses which has the biggest array dimension such as $segment[0][0] which gives result of 3 and stored it again in $segment[0][0]. And the rest of evaluation will goes slightly different from the previous equation to get the result of t. My explanation might be hard to be understood and also might have silly way of doing it, but hope you can understand and help to improve, thank you.