Hiru
Hiru

Reputation: 103

Finding the next value of an array

Here I need to check whether the value comes after 1 is 1.1. Next value comes after 1.1 is 1.2. etc.

The next value after a given value is takes by $C=$A[i]+'.'+$count; but when I print it prints values 1,2,3,4 etc. Is the way I have approached to the problem incorrect.

<?
$A=array(1, 1.1, 1.2, 1.3, 1.4);

$count=0;

for($i=0;$i<sizeof($A);$i++){
$count++;
$B=$A[$count];
$C=$A[i]+'.'+$count;

if($B==$C){
//a code goes here

}
}
?>

Upvotes: 1

Views: 93

Answers (2)

I hope this is what you are looking for.

<?php
$a=array(1, 1.1, 1.2, 1.3, 1.4);
$count=0;

foreach($a as $v)
{
    $c = "1".'.'.$count;
    if($c==$v)
    {
       echo "Match Found";
    }
    $count++;

}

?>

Upvotes: 1

user1320635
user1320635

Reputation:

You had a lot of syntax error, every variable in php must be prefixed with $. You missed that on the i-variable a couple of times. You also missed brackets in the for-loop. And your $A variable was printed out because it was written before the PHP-tag.

I cleaned it up and corrected those issues:

$A = array(1, 1.1, 1.2, 1.3, 1.4);
$count = 0;

for($i = 0; $i < sizeof($A) - 1; $i++){
    $count++;
    $B = $A[$count];
    $C = $A[$i] + 0.1;

    if($B == $C){
        // This will be executed every time the next value is "current + 0.1".
    }
}

Upvotes: 1

Related Questions