Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fatal error: Cannot unset string offsets error?

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,

like image 836
Jared Avatar asked Sep 05 '12 21:09

Jared


3 Answers

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.

like image 98
Tom Avatar answered Oct 15 '22 12:10

Tom


I had this error in a slightly different situation which might prove useful.

unset($search['param']['complete'])

This threw the same error when $search['param'] was still a string instead of an array.

like image 10
Steve Tauber Avatar answered Oct 15 '22 13:10

Steve Tauber


I believe that you have the syntax for the foreach wrong...it should be $key => $value where you have $key => $arr2. So when you have $arr2[$key] you are looking for element $key in the nested array $arr2. $arr2 is referenced by $key, which is either a string (for an associative array) or an integer (for a non-associative array). $arr2 could also be referenced by $arr[$key].

http://php.net/manual/en/control-structures.foreach.php

like image 2
taz Avatar answered Oct 15 '22 14:10

taz