Fatal error: Cannot unset string offsets error?

Jared picture Jared · Sep 5, 2012 · Viewed 46.8k times · Source

Not sure why this is occurring: Basically, I have an array that contains the following arrays, see var_dump:

array(2) { 
  [0]=> array(1) { 
    [0]=> string(3) "ivr" 
  } 
  [1]=> array(1) { 
    [0]=> string(9) "ivr_dests" 
  } 
}

Obviously this data is kind of redundant, but it's what was returned while getting values with xpath. So I'm doing a foreach to loop through the first array() and assign it's nested array values in the first array.

Basically, it should return this:

array(2) {
  [0]=> string(3) "ivr"
  [1]=> string(9) "ivr_dests"
}

So here is what I've setup:

foreach($arr as $key => $arr2){
    $arr2[$key] = $arr2[$key][0];
    unset($arr2[$key][0]); //This returns Fatal error: Cannot unset string offsets
//if I comment out the unset(), $arr[$key] returns the same value as it did (multidim array)
};

        //I tried this too:
$i=0;
foreach($arr as $arr2){
  $arr2[$i] = $arr2[$i][0];
  $i++;
}

Any ideas what I'm doing wrong? Should I go about this another way?

Thanks,

Answer

Tom picture Tom · Sep 5, 2012

You don't need the unset, you are overriding the outer parameters with the value of the inner array as opposed to the whole array.

$a1 = array("ivr");
$a2 = array("ivr2");

$a3 = array($a1, $a2);

foreach($a3 as $key => $value){
    $a3[$key] = $a3[$key][0];
    //unset($arr2[$key][0]);
};

var_dump($a3);

I think you are confused about how foreach works.

foreach($array as $key => $value)
{
  echo $key;
  echo $value;
}

will display the key and value for each key/value pair in an array.