I have a problem that I need to solve.
I have an associative array, eg:
private $formData = [
"lastPrintedNumber" => 0,
];
I obtain this data from a text file with a function…:
$line = fgets( $formDataFile );
$explodedLine = explode( ' ', $linea );
$this->formData[ 'lastPrintedNumber' ] = (int) $explodedLine[2];
It assigns the correct type, int, to $formData[ lastPrintdNumber ].
But I don’t want to hardcode the assignments, instead I want to do a foreach, looking for the right data in the array.
Example:
$line = fgets( $formDataFile ) ) != false ) {
$explodedLine = explode( ' ', $linea );
foreach( $this->formDatos as $key => $value ) {
if( $explodedLine[0] == $key ) {
$this->formData[ $key ] = $value;
}
}
The problem is that it assigns the value as string, and in some case I need int for maths.
So I would need a way to stablish the data type for formData[ 'lastPrintedNumber' ] to always be int.
Thanks a lot.
Just a small point: You should be using
==in theif, not just=.That aside, it doesn’t matter like it does in JavaScript. In JS, if you have
a = "1"; b = "2"; alert(a+b)you get12, but in PHP you get 3 because+expects numbers.PHP’s type coercion solves almost all problems by itself, so there’s usually no need to specify a certain type.