Reputation: 1621
I am trying to check for a value in a given list of csv values. I have the following code that in theory should work. But for some reason its not. Not sure what i am doing wrong here. Can someone please help.
$string = "5,9,10,13";
function checkDay($day, $list){
if (strpos($list, $day) !== FALSE) {
return TRUE;
} else {
return FALSE;
}
}
for ($x=0; $x<=15; $x++) {
if(checkDay($x, $string)){
echo "There is an event on " . $x . "<br>";
}else{
echo "There is NO event on " . $x . "<br>";
}
}
Upvotes: 0
Views: 67
Reputation: 5090
If you absolutly wants it to work that way (In the case where you were just giving an example that wouldn't work with explode), you could just typecast your $x
to string when you call your function :
if(checkDay((string) $x, $string)){
Upvotes: 1
Reputation: 444
$string = "5,9,10,13";
$days = explode(',', $string);
for ($x = 0; $x <= 15; ++$x) {
if (in_array($x, $days)) {
echo "There is an event on $x.<br/>";
} else {
echo "There is NO event on $x.<br/>";
}
}
Example (uses \n instead of <br/>)
Upvotes: 2
Reputation: 219874
That code won't work like you think. A day of 3
will return true if 131
is in your list of dates.
A better way to do this is to put your dates into an array and check to see if your day is a value in that array. That if/else statement is also unnecessary.
$string = "5,9,10,13";
function checkDay($day, $list){
$dates = explode(',', $list);
return in_array($day, $dates);
}
for ($x=0; $x<=15; $x++) {
if(checkDay($x, $string)){
echo "There is an event on " . $x . "<br>";
}else{
echo "There is NO event on " . $x . "<br>";
}
}
Upvotes: 1