CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 4 of 4
  1. #1
    Join Date
    Apr 2009
    Posts
    38

    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

  2. #2
    Join Date
    Jan 2010
    Posts
    1

    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...

  3. #3
    Join Date
    Apr 2009
    Posts
    38

    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

  4. #4
    Join Date
    Feb 2010
    Posts
    2

    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
  •  





Click Here to Expand Forum to Full Width

Featured