Selecting array elements in PHP

614

So I have the following array:

$ISBN = '0,1,9,8,5,x,8,0,3,0';

$inArray = explode(',',$ISBN);

While this loop prints the numbers 10-1 like so10 9 8 7 6 5 4 3 2 1:

for($i=10; $i>0; $i=$i-1)
{
    echo $i." ";
}

I want to multiply each element accordingly starting from the first one. For example:10*inArray[0] + 9*inArray[1] + 8*inArray[2] and when it hitsx to print it like6*x for example; etc.

2

Answer

Solution:

Something like this:

$factor = count($inArray);
foreach($inArray as &$value) {
    if($value != "x") {
       $value *= $factor;
    } else {
       $value = $factor.'*'.$value; 
    }
    $factor--;
}
unset($value);

Value of$inArray would be:

0,9,72,56,30,5*x,32,0,6,0

People are also looking for solutions to the problem: PHP array loop, accessing by numeric index

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.