-
January 29th, 2010, 11:46 AM
#1
Problem with Arrays and comparisons
I am trying to run this code:
Code:
@row1 = ('1','2','4','5','6','8','9');
for($i=1; $i<=9; $i++){
if(@row1 =~ /$i/){
print "$i worked\n";
}
}
I idea is that it prints:
1 worked
2 worked
4 worked etc...
However, the only thing it outputs is '7' worked, which I think is because the array is 7 elements long?
Without introducing another loop(because that will make my final task a lot harder), how can I see if an element exists in an array? I've tried using if(exists($row1[$i])){} but with no luck.
How can I get the desired output?
Any help will be greatly appreciated
--Sam Kennedy
-
January 31st, 2010, 04:10 AM
#2
Re: Problem with Arrays and comparisons
In PHP it would be:
PHP Code:
if(in_array($i, $row1))
To check if a value is inside the array, and:
PHP Code:
if(array_key_exists($i, $row1))
To check if the key exists inside the array.
But as Im not sure which language this was meant to be for...
-
February 1st, 2010, 03:43 PM
#3
Re: Problem with Arrays and comparisons
Whoops sorry, it's in perl. I found out I simply needed to put the array in quotes to get the contents rather than the length.
Sorted
-
February 2nd, 2010, 10:53 AM
#4
Re: Problem with Arrays and comparisons
Of course you could keep it in php:
#!/usr/bin/php -q
<?php
$row = array('1','2','4','5','6','8','9');
for($i=1; $i<=9; $i++) {
if($row[$i] != $i){
print "$i worked\n";
}
}
?>
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|