Fahad Sohail
Fahad Sohail

Reputation: 1836

Foreach returns only one output

Okay so I am stuck here and I know there would be a simple solution, but I can't figure it out. So the thing is that I have a function which creates columns in a database if not exists. I got the function to work but I want to add the functionality in the function of detecting the column type (VARCHAR, INT etc) and creating columns accordingly. I am trying to get this done by gettype keyword. Now, $productData is in array so I need to apply foreach to get them separated and then I get the value type, the problem is that in the end foreach loop, it gives me only string. Where $productData has 4 strings and 1 integer ..

$array       = (array) $productData;
$arrayValues = array_values( $array );
$i = 0;

foreach ( $arrayValues as $key => $value ) {
    $types = array( "id-$i" => gettype( $value ) );
    $i++;
}
var_dump($types);

Can somebody help me out there please?

Thanks ..

Upvotes: 2

Views: 1429

Answers (2)

fejese
fejese

Reputation: 4628

You need to initialise the array only once and add elements to it later:

$array       = (array) $productData;
$arrayValues = array_values( $array );
$i = 0;

$types = array();
foreach ($arrayValues as $key => $value) {
    $types["id-$i"] = gettype($value);
    $i++;
}
var_dump($types);

Be careful with gettype() as it will fail on bojects. You need to make sure that each $value is an internal type

Update: The gettype() will return "object" for all objects. So it is a safe way to determine the type of a variable. Although in case you need the class of the object you need to use get_class() in case gettype() returns "object"

Upvotes: 4

James McClelland
James McClelland

Reputation: 555

If you are selecting the table definitions first using the MYSQL command: SHOW COLUMNS FROM mytable that will return an array of columns with their definitions

Upvotes: 1

Related Questions