Jump to content

type casting


jimfog
 Share

Recommended Posts

My q has to do with type casting. In what programming scenarios do we usually use it? I have not encounter so far a case where I would need to convert a variable from one data type to another.

Link to comment
Share on other sites

You use it to convert database numbers, which are returned as strings, into PHP integers or floats.You also use it to convert information sent through GET, POST, COOKIE and others which are strings, into numbers. Every time you print a value from PHP the value is automatically being typecasted to string.

Link to comment
Share on other sites

as php is loosly typed language most of the time it implicitly be auto type casted (eg when you use arithmatic oprator,comparison oprator) in some scenerio some of them as ingolme said you need to type caste to ensure explicitly set the types rather than depending php auto type casting to avoid any misstakes and future bugs. in strict languages the rules are stricter so thus it iis essential to set the type. though It is good practice to set types even in loosly type languages.

Link to comment
Share on other sites

You use it to convert database numbers, which are returned as strings, into PHP integers or floats.You also use it to convert information sent through GET, POST, COOKIE and others which are strings, into numbers.
That's the key point with PHP - when you're dealing with a MySQL database extension (others may differ), or any sort of user input, everything ends up as a string in PHP. You may have database or form fields that are numbers or dates or whatever where it would be safer to convert to their correct type before you do anything else with them. Here's a pair of functions to get the field info from a table and convert an array of rows to native data types (int, bit, float, double, decimal, boolean, you could add support for DateTime objects also). The array of rows would be something that you would build by looping through a result set using mysql(i)_fetch_assoc and adding each row to an array.
<?php/**************************get_fieldsReturn an array of information about the fields in the table.params:  $table: the table to get information aboutreturn:  an associative array with 'field' and 'type' elements containing  the name and data type of each field**************************/function get_fields($table){  if ($table === '')    return false;  $retval = array();  $result = mysql_query("SHOW FIELDS FROM {$table}");  while ($row = mysql_fetch_array($result))    $retval[] = array('field' => $row['Field'], 'type' => $row['Type']);  return $retval;}/**************************transform_rowsetCasts each value in the rowset to the native data type in thegiven table.The MySQL PHP extension will always return string values for allcolumns.  This function will convert int, bit, float, decimal,double, and boolean fields to the native PHP types.params:  $rows: the rowset returned from the select method  $table: the table name the rows came fromreturn:  the converted rowset**************************/function transform_rowset($rows, $table){  if (!is_array($rows) || count($rows) == 0 || $table === '')    return $rows;  $tf = get_fields($table);  $fields = array();  foreach ($tf as $f)    $fields[$f['field']] = $f['type'];  if (count($fields) == 0)    return $rows;  foreach ($rows as $k => $v)  {    foreach ($v as $f => $val)    {	  if (!isset($fields[$f]))	    continue;	  if (stripos($fields[$f], 'int') !== false ||		  stripos($fields[$f], 'bit') !== false)	  {	    $v[$f] = intval($val);	  }	  elseif (stripos($fields[$f], 'float') !== false ||			  stripos($fields[$f], 'decimal') !== false ||			  stripos($fields[$f], 'double') !== false)	  {	    $v[$f] = floatval($val);	  }	  elseif (stripos($fields[$f], 'bool') !== false)	  {	    $v[$f] = (bool)$val;	  }    }    $rows[$k] = $v;  }  return $rows;}?>

Link to comment
Share on other sites

as php is loosly typed language...
Since you mentioned the term "loosely typed", does that mean that we do NO NEEDto specify the type of cast-in PHP this being done auto into strings?
That's the key point with PHP - when you're dealing with a MySQL database extension (others may differ), or any sort of user input, everything ends up as a string in PHP. You may have database or form fields that are numbers or dates or whatever where it would be safer to convert to their correct type before you do anything else with them. Here's a pair of functions to get the field info from a table and convert an array of rows to native data types (int, bit, float, double, decimal, boolean, you could add support for DateTime objects also). The array of rows would be something that you would build by looping through a result set using mysql(i)_fetch_assoc and adding each row to an array.
<?php/**************************get_fieldsReturn an array of information about the fields in the table.params:  $table: the table to get information aboutreturn:  an associative array with 'field' and 'type' elements containing  the name and data type of each field**************************/function get_fields($table){  if ($table === '')	return false;  $retval = array();  $result = mysql_query("SHOW FIELDS FROM {$table}");  while ($row = mysql_fetch_array($result))	$retval[] = array('field' => $row['Field'], 'type' => $row['Type']);  return $retval;}/**************************transform_rowsetCasts each value in the rowset to the native data type in thegiven table.The MySQL PHP extension will always return string values for allcolumns.  This function will convert int, bit, float, decimal,double, and boolean fields to the native PHP types.params:  $rows: the rowset returned from the select method  $table: the table name the rows came fromreturn:  the converted rowset**************************/function transform_rowset($rows, $table){  if (!is_array($rows) || count($rows) == 0 || $table === '')	return $rows;..... }?>

At some points in the code above it is mentioned "return row". I know this is off-topic but I am asking cause it will help meunderstand the code better. With return, we exit a function early, now, in the above case does that mean that the function outputs only the $row(no more lines of code are processed)?
Link to comment
Share on other sites

At some points in the code above it is mentioned "return row". I know this is off-topic but I am asking cause it will help meunderstand the code better. With return, we exit a function early, now, in the above case does that mean that the function outputs only the $row(no more lines of code are processed)?
http://php.net/manual/en/function.return.php
Link to comment
Share on other sites

Since you mentioned the term "loosely typed", does that mean that we do NO NEEDto specify the type of cast-in PHP this being done auto into strings?
yes. it is auto type casted but not necessarily to strings. it could be other types also http://php.net/languages.type <= if you check every types here you can see how one data type is converted to another.
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...