-2

I'm getting some weird behaviour in PHP that I just can't understand.

    $count=0;
    $temp=array(); //this is definitely a new variable, not that it should matter
    foreach($array as $arr) {
        if ($arr->bbcode != $previous_bb) {
            $previous_bb=$arr->bbcode; 
            //stuff
            $temp=array_merge($temp,$arr);
         }
     //stuff
    }

I've tried to simplify the code a little and just keep what's essential. $array is a 2-D array (so each $arr has some attributes like the bbcode that you see). It complains that argument 1, i.e. $temp, is not an array. Typecasting it to array gives bogus results. Of course, this is within other code, which I can give more details of if needed, but any ideas? I've used the exact same sort of code and syntax in other places and it doesn't complain...

EDIT: Feel free to downvote liberally, had a memory lapse about what I had been working with and how I'd been doing things. Never had to ask a programming question before (in several years), thanks a ton guys, you are immensely fast!

ShakesBeer
  • 283
  • 4
  • 15

2 Answers2

1

Let's look at your two arguments.

  • $temp is initialised as array(), and repeatedly assigned to the return value of array_merge which (unless things go wrong) is always an array.

  • $arr. Well, it's in the name, right? That's about as reliable as $two = 3;. You are accessing $arr->bbcode so it is clearly an object and not an array.

Did you mean $temp[] = $arr;?

Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
  • True that, and what I've done isn't exactly exemplary programming. Why has it worked elsewhere then (In exactly the same sort of situation)? Edit: OK, I see what I did differently. – ShakesBeer Jul 18 '14 at 10:55
0
  1. You are trying to merge an object ($arr) with an array ($temp). PHP should complain that $arr is not an array. See the example code below:

    php > $obj = new StdClass();
    php > $obj->property = "value";
    php > $arr = [];
    php > array_merge($arr, $obj);
    
    Warning: array_merge(): Argument #2 is not an array in php shell code on line 1
    
    Call Stack:
       33.2510     230352   1. {main}() php shell code:0
       33.2510     230960   2. array_merge() php shell code:1
    
  2. Typecasting in php is always a bit tricky, if you do so check the type juggling documentation to see what happens when.

  3. Before trying to optimize your code, what do you want to achieve? A new list which is cleaned of duplicate bb codes?

Ota
  • 696
  • 3
  • 11
  • For some reason it was complaining about the wrong argument, which I won't try to figure out why, and was part of the source of my confusion. Thanks for the good answer :) As for 3, no, and this is the most efficient way of doing what I'm trying to achieve – ShakesBeer Jul 18 '14 at 11:01