Jump to content

Using an if statement to unset array keys?


ash992
Go to solution Solved by Ch0cu3r,

Recommended Posts

Hey guys so I've been trying to figure something out for a day now but I really don't know where to start, basically I'm trying to create some kind of function that goes through my array and checks if the keys value is less than 5, if it is then I want to unset the key removing it from the array,

 

I programmed this underneath as this is basically what I want to achieve however there's a syntax issue as the array_key_excists function doesn't seem to allow the if statement, if anyone knows anything about it it would be very helpful!

if (array_key_exists(($key > 5),$data))
 {
    unset($data[$key]);
 }

any help is very much appreciated,

 

Thanks very much in advance!

 

Link to comment
Share on other sites

Hmm there's a few different problems, I'm creating my array from a csv file, after the third comma on every line it has a number that I want to check if it's less than 10,

$data = fgetcsv($handle, 12000, ","

(this is where I create the variable that reads the csv file)

 

is it possible to pick a specific row in the key to check? or should I try to find a different method of doing this?

 

Thank-you very much for the help and quick response! much appreciated 

Link to comment
Share on other sites

  • Solution

So you want to ignore rows where the 4th column has value less than 10? In that case you'd do something like this

$data = array();
if (($handle = fopen("data.csv", "r")) !== FALSE) {
    while (($row = fgetcsv($handle, 1000, ",")) !== FALSE) {
           // only add rows to the array where the 4th column value is greater than or equal to 10
            if($row[3] >= 10)
                $data[] = $row;
        }
    }
}
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.