Reputation: 41
So I am trying to check to see if this array has an underscore in it. I am not sure if I am using the correct function to do this. Any input would be appreciated.
Some more info, if the array does have an underscore I want it to run the code below. This code seperates and gives me the attributes that I want. I also check if it has and S and then run some code. These are all output to queries which are then queried at the end.
if (count($h)==3){
if (strpos($h[2], '_') !== false) // test to see if this is a weird quiestion ID with an underscore
{
if (strpos($h[2], 'S') !== false)
{
// it has an S
$underscoreLocation = strpos($h[2], '_');
$parent = substr($h[2], 0, $underscoreLocation - 6); // start at beginning and go to S
$title = substr($h[2], $underscoreLocation - 5, 5);
$questions = "select question from lime_questions where sid =".$h[0]." and gid =".$h[1]." and parent_qid =".$parent." and title =".$title.";";
}
else
{
// there is no S
$underscoreLocation = strpos($h[2], '_');
$parent = substr($h[2], 0, $underscoreLocation - 2);
$title = substr($h[2], $underscoreLocation - 1, 1);
$questions = "select question from lime_questions where sid =".$h[0]." and gid =".$h[1]." and parent_qid =".$parent." and title =".$title.";";
}
}
else
{
$questions = "select question from lime_questions where sid =".$h[0]." and gid =".$h[1]." and qid =".$h[2].";";
}
Upvotes: 0
Views: 101
Reputation:
strpos() is a good function to use when checking to see if a substring exists within a string, so your basic premiss is fine.
The haystack you're submitting to the strpos() (i.e. $h[2]) is a string , isn't it? You say in your question that you're checking if an array contains an underscore, but the code only checks to see if a single array item contains an underscore - these are two very different things.
If $h[2] is a sub array instead of just a string within the $h array then you need to iterate through the subarray and check each item.
so:
for ($x=0; $x<count($h[2]); $x++) {
if (strpos($h[2][$x], "_")!==false) {
if (strpos($h[2][$x], 'S') !== false) {
// Run code
} else {
// Run code
}
}
}
If $h[2] is just a string then what you have should be fine.
Update: try adding
print($h[2][$x].' - '.strpos($h[2][$x], ''));
on the line before
print ($h[2][$x].' - '.strpos($h[2][$x], ''));
This should give us an idea of what the problem is.
Update:
Based n the code we just ran things are very different from what I thought. First of all, not all of the $h arrays returned have 3 items. Secondly $h2 is a stirng, not a subarray.
so here's the new code:
if (count($h)==3) {
print($h2.' | ');
if (strpos($h[2], "_")!==false) {
print(' underscore was found | ');
if (strpos($h[2], 'S') !== false) {
// Run code
} else {
// Run code
}
}
} else {
// array does not represent a question
}
Also, you need to change all of the $h[2][$x] back to just $h[2]. Tell me how it goes.
Upvotes: 1