I managed to do this before somehow and have forgotten how to do it. I keep getting an undefined offset notification for element associations (e.g. where $arr[$i] => "something"). E.g. for the following:
for($i=0;$i<count($arr);$i++) {
if($a = strstr($arr[$i], "str"))
{
print "Found: ". $a. "<br>";
}
else {
if($i >= count($arr))
{
print "Couldn't find <i>str</i>.<br>";
return false;
}
}
}
That won't work and will output an undefined offset notification. Any help is greatly appreciated!
for($i=0;$i<count($arr);$i++) {
if($a = strstr($arr[$i], "str")) {
print "Found: ". $a. "<br>";
} else {
if($i >= count($arr)) {
print "Couldn't find <i>str</i>.<br>";
return false;
}
}
}
First if function was missing a bracket.
I added the bracket you were missing in second line and it works for me
for($i=0;$i<count($arr);$i++) {
if($a = strstr($arr[$i], "str")) {
print "Found: ". $a. "<br>";
} else {
if($i >= count($arr)) {
print "Couldn't find <i>str</i>.<br>";
return false;
}
}
}
You should iterate trough array with foreach
loop, not with for
. Your code should look like this:
foreach( $arr as $item){
if(($a = strstr($item, "str")) !== false){
print "Found: ". $a. "<br>";
}
}
strstr()
may return ''
when it matches on last character, therefor use !== false
Returns the portion of string, or FALSE if needle is not found.
for
anywayYou have to be able to handle associative arrays as well:
$arr = (
'key1' => 'val1',
'key2' => 'val2',
...
);
Than you'd have to use code like this:
$keys = array_keys( $arr);
$count = count( $keys);
for( $i = 0; $i < $count; $i++){
$item = $arr[ $keys[$i]];
}
Use foreach
instead .)
Did you say something like this?
foreach ($arr as $value) {
if(strstr($value, $a)) {
print "Found: ". $a . "<br />";
}
}
For the print you want to show, I imagine that the $a is what you're looking for in this array.