Hi... I got the following:

``````function solution(\$A) {
if (is_array(\$A)) {
if (\$b = preg_grep("/\-1/", \$A)) {
foreach (\$b as \$key => \$value) {

\$A_count = count(\$A);
\$remove = (\$A_count-1) - \$key;
\$v = \$A[\$key];
unset(\$A[\$key]);
for(\$i = \$key+1; \$i < \$A_count; \$i++){
unset(\$A[\$i]); // to remove the element after -1
}
\$A[\$key] = \$v;

print_r(\$A);
\$result = count(\$A);

}
}

}
return \$result;
}

print_r(solution(array(1, 4, -1, 3, 2))); // returns 4
print_r(solution(array(2, -1, 1, 0, 0, 0))); // returns 3
print_r(solution(array(2, 1, 1, 0, 0, 0, -1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0))); // returns 8
``````

I need the function to return 4 at all times. -1 is the last element of the array. please help?

What exactly are you trying to achieve with the function?

## All 2 Replies

What exactly are you trying to achieve with the function?

it was a question in a test I wrote:
I was told that if given an array cosisting of any number of integers, constructed as follows:
the first element is located at index 0,
the value of a element located at index K is A[K],
next-in-line of a element located at index K is located at index A[K],
if the value of a element is −1 then it is the last element of the array.

then I was told to write a function that returns four. I was told to take into consideration that the array can consist of 1-200000 elements,
each element can be a number of between -1 and 200000 and that it will always be possible to construct the array and its length will be limited

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.