Forum Moderators: coopster
For example: www.dsgfsd.com...php?a=144ab5df7 - script have to print "yes" because there is one or more numbers which are suare of toher number. (in this example it is 144, because 12*12 = 144)
What i already have:
<?php
$str = $_GET['a'];
//i understood, that here i had to extract numbers from the string and than put them into array, but how to do this? i read about preg_match function. Can i do with it?
$arr = str_split($str);
for ($i=0; i<.count($arr);$i++;)
if (round(sqrt($arr[i]))==sqrt($arr[i]))
{
echo "yes"
}
else
{
echo "no"
}
?>
IF someone can help it would be very nice!
Thank you!
[edited by: eelixduppy at 2:45 pm (utc) on Oct. 8, 2009]
[edit reason] disabled smileys [/edit]
<?php
$str = $_GET['a'];
$pattern = "/([\d]+)/";
preg_match_all($pattern, $str, $arr);
print_r($arr)
for ($i=0; i<.count($arr);$i++;)
if (round(sqrt($arr[i]))==sqrt($arr[i]))
{
echo "yes"
}
else
{
echo "no"
}
?>
[edited by: eelixduppy at 2:45 pm (utc) on Oct. 8, 2009]
[edit reason] disabled smileys [/edit]
<?php
$str = $_GET["a"];
$pattern = "/([\d]+)/";
preg_match_all($pattern, $str, $arr);
for ($i = 0 ; i < count($arr); $i++)
{
if (round(sqrt($arr[i])) == sqrt($arr[i]))
{
echo "yes";
//exit;
echo $i;
};
};
echo "No";
?>
So... i tried this one, but it prints only "yes".
Can anyone help, please?
if (round(sqrt($arr[i])) == sqrt($arr[i]))
Should be:
if (round(sqrt($arr[$i])) == sqrt($arr[$i]))
<?php
$str = $_GET["a"];
$pattern = "/([\d]+)/";
preg_match_all($pattern, $str, $arr);
for ($i = 0 ; i < count($arr); $i++)
{
if (round(sqrt($arr[i])) == sqrt($arr[i]))
{
echo "yes";
//exit;
echo $i;
};
};
echo "No";?>
Here's a corrected version:
In addition to the correction noted above...
I added the $ to i in the for.
Moved the echo "No"; inside the for loop.
Added an else with it, otherwise it will always echo 'No' at the conclusion of the for.
(Both echo statements could probably be moved outside the script after testing if a yes / no is required fairly easily by setting a variable to check and then referencing it at the conclusion of the for, so rather than echo 'Yes' / 'No' within the for, set $MatchFound=1; where echo 'Yes' is, then use an if after the loop if($MatchFound===1) { echo 'Yes'; } else { echo 'No'; })
Removed extra ;'s from after the }.
<?php
$str = $_GET["a"];
$pattern = "/([\d]+)/";
preg_match_all($pattern, $str, $arr);
for ($i = 0 ; $i < count($arr); $i++)
{
if (round(sqrt($arr[$i])) == sqrt($arr[$i]))
{
echo "yes";
//exit;
echo $i;
}
else {
echo "No";
}
}
?>
The main problem was: You were attempting to compare the rounded sqrt() of array piece 'i' to the sqrt() of array piece 'i' which was not set, and will always evaluate to 'true', because they are always equal... Basically the comparison was not looping with your counter. Also, the echo 'No'; was outside the loop, so it would not have echoed as expected...