Question

So I have an associative array, $data, pulled from a $_POST. Looping through with a foreach to reorder things as I want them for later in the program, like moving certain key->values into a "privacy" array as below, and I've come across a snag trying to unset some elements here:

public function create_profile($data, $files, $status) {
        $files = $files['files'];
        unset($files['files']);
        $privacy = array();
        foreach ($data as $key => $value) {
            if (strpos($key, 'privacy') !== false) {
                $privacy[$key] = $value;
                unset($data[$key]);
            }
            if (($key == 'filename') || ($key == 'fileyear')) {
                $files[$key] = array();
                for ($i = 0; $i < sizeof($data[$key]); $i++) {
                    if ($data[$key][$i] != '') {
                        $files[$key][$i] = $data[$key][$i];
                    }
                }
            } else {
                $data[$key] = $value;
            }
            unset($data['filename']);
            unset($data['fileyear']);
        }

        $tokenized_name = str_replace(' ', '_', $data['display_name']);
        return($data);
}

The privacy array print_r's what it should, so I know it's finding the right elements, but it's not unsetting them, and I can't for the life of me think why. Which means it's surely something really dumb.

Was it helpful?

Solution

I'll assume that your $data array have something like this: $data['privacy'] = 'foo'; $data['privacy-something'] = 'bar'; $data['test'] = 'foobar';

In this situation strpos($key, 'privacy') will not work correctly as if statement will return false for 0 value.

Also there was small brace problem at the end. So code that work perfectly for me looks like this:

$privacy = array();
foreach ($data as $key => $value) {
    if (strpos($key, 'privacy') !== false) {
        $privacy[$key] = $value;
        unset($data[$key]);
    }
}

EDIT

Problem is here:

else {
    $data[$key] = $value;
}

You're setting unset value again. Why you need this?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top