How can i create a new array from elements in associative array in the way that if values is integer then put that value on first place in a new array,on the second place put double,on the third place string, and on the last place number of elements. I try something like this but it doesn’t work.
<?php
$array = array ('first' => 2.54, 'second' => "foo", 'third' => 1);
function myFunction($array)
{ $NewArray = array ();
$[3] = 0;
foreach($array as $value)
{
if(is_integer($value))
{echo $NewArray[0] = $value.' ';}
if(is_double($value))
{echo $NewArray[1] = $value.' ';}
if(is_string($value))
{echo $NewArray[2] = $value.' ';}
echo $NewArray[3] += 1 . ' ';}
return $NewArray;}
MyFunction ($array);
?>
Mathieu Imbert is right and you didn’t describe what was wrong when you ran the code. I corrected it based on what
myFunctionshould return (as specified in your question).You shouldn’t concatenate those values with string
' 'unless you want it with the space after the value. Finally if you want number of elements on 3rd position in returned array, don’t concatenate the counter with' '– with that concatenation the counter would be'1 1 1 '(for sample array from your question). Without it –3.Here’s the corrected, tested code (I took the liberty of reformatting your code to make it easier to read and added
print_r()for prettier output):which outputs: