Hello, I was trying to extract the values of the associative array, but I couldn't figure out how to get them out. When I run this code, I get an warning saying: Warning: Invalid argument supplied for foreach()

<?php
	// Append associative array elements
	$order = array();
	function array_push_associative(&$arr)
	{
	   $args = func_get_args();
	   foreach ($args as $arg)
	   {
	       if(is_array($arg))
		   {
	           foreach ($arg as $key => $value)
			   {
	               $arr[$key] = $value;
	               $ret++;
	           }
	       }
		   else
		   {
	           $arr[$arg] = "";
	       }
	   }
	   return $ret;
	}
	$i = 0;
	while($i < 5)
	{
		$myArr = array($i => "hello");
		$order .= array_push_associative($myArr);
		$i++;
	}

   // This causes an error
foreach($order as $key => $value)
{
	echo "Our key $key is $value\n";
}

print_r($order);
?>

    Probably because you are using a string concatenation operator on $orders in your while loop. That, effectively, changes your $order variable from an array to a string.

    Hello, I was trying to extract the values of the associative array

    Why not just use the array_values() function?

      How would I concatenate the array instead of using the string? I tried += but that didn't work.

        adaykin;10878447 wrote:

        How would I concatenate the array instead of using the string? I tried += but that didn't work.

        You don't concatenate to an array. You push to it.

        $order[] = array_push_associative($myArr);
        //or...
        array_push($order, array($i => "hello"));
        

          Ahh the [] was what I was missing, I had tried just $order = array_push_associative($myArr);

          Thanks, I got it working now.

            Right, in your example you needed to push and array to an existing array. Of course $order = array_push_associative($myArr); just reset the array for each iteration.

            Thanks, I got it working now.

            Awesome!

              Well now that I can see the array keys and values, it's not extracting the right values. The value for each key is 1, instead of hello. Why aren't the values in each associative array "hello"?

                Because your array_push_associative function returns an integer, not the array that was sent to it. Since, you send exactly one array element with each array , $ret gets incremented just once...

                //...
                if(is_array($arg)) //it is in your example each time.
                {
                   foreach ($arg as $key => $value)
                   {
                       $arr[$key] = $value;
                       $ret++; //increment by one
                   }
                }
                //...
                return $ret;
                  Write a Reply...