Question

Ok then. I have a filled array defined like this:

$subs = array();
for (...) {
    // extracting of variables $knowledgeLevel, $name, $short, $long
    $subs [] = array (
         'knowledgeLevel' => $knowledgeLevel,
         'name' => $name,
         'shortTheory' => $short,
         'longTheory' => $long
    );
}

then I receive a value $kl, and I want to eventually delete from the array $subs the element that has the knowledgeLevel equal to $kl. I've tried to do so:

foreach ( $subs as $subject ) {
    if ($subject['knowledgeLevel'] == $kl) {
        unset ($subject);
    }
}

and so

foreach ( $subs as $subject ) {
    if ($subject['knowledgeLevel'] == $kl) {
        unset ($subject['knowledgeLevel']);
        unset ($subject['name']);
        unset ($subject['shortTheory']);
        unset ($subject['longTheory']);
    }
}

but these don't seem to work.

Was it helpful?

Solution

In order to be able to directly modify array elements within the loop precede $value with &. In that case the value will be assigned by reference.

Use & with foreach ( $subs as &$subject )

foreach ( $subs as &$subject ) 
    if ( $subject['knowledgeLevel'] == $kl ) 
        unset ($subject);

Or try this:

This form will additionally assign the current element's key to the $key variable on each iteration.

foreach ( $subs as $key => $subject )
    if ( $subject['knowledgeLevel'] == $kl ) 
        unset( $subs[$key] );

OTHER TIPS

$subject is not reference to $subs it's new variable and with unset($subject['anything']) you are not deleting anything from $subs

Use for loop:

for($i=0;$i<count($subs);$i++) {
   if ($subs[$i]['knowledgeLevel'] == $kl) {
       unset ($subs[$i]);
   }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top