I’m trying to understand the importance of initializing a variable, before assigning a value to it in those rare cases where for example, you might be creating an array within a loop.
For example;
foreach($var1 as $key => $val) {
$array[] = $key;
}
In this example, $array hasn’t been declared before it’s used to contain an array, which I’ve been told is bad practice, but I have no idea why. I’ve been advised to instead do this;
$array = array();
foreach($var1 as $key => $val) {
$array[] = $key;
}
Another example, when constructing a long string based on many array values:
$size = count($array);
for($i = 0; $i < $size; $i++) {
$string .= $array[$i]."del".$array_2[$i].",";
}
I’ve been told it should be done like this
$string = null;
$size = count($array);
for($i = 0; $i < $size; $i++) {
$string .= $array[$i]."del".$array_2[$i].",";
}
I’m wondering why, in both these cases, it’s advised to initialize the variable before assigning data to it? Or this not the case, and I’ve simply heard wrong. Are there exceptions to this rule, if it does exist?
Update: Would this be the proper way to initialize variables in this function?
function weight_index($keyword, $src, $alt, $content, $ratio='3:3:1') {
// Initialize needed variables
$content_index = ''; $src_index = ''; $alt_index = '';
// Create all four types of $keyword variations: -, _, %20, in order to search
// through $content, $alt, $src for instances.
$keyword_fmt = array('hyphen' => str_replace(' ', '-', $keyword), 'underscore' => str_replace(' ', '_', $keyword), 'encode' => urlencode($keyword), 'original' => $keyword);
// Define weight index for each instance within a searchable "haystack".
list($src_weight, $alt_weight, $content_weight) = explode(':', $ratio);
// Get the number of instances of $keyword in each haystack for all variations.
foreach($keyword_fmt as $key => $value) {
$content_index += substr_count($value, $content); // .. may generate an error as $x_index hasn't been initialized.
$src_index += substr_count($value, $src);
$alt_index += substr_count($value, $alt);
}
// Multiply each instance by the correct ratio.
$content_index = $content_index * $content_weight;
$src_index = $src_index * $src_weight;
$alt_index = $alt_index * $alt_weight;
// Total up all instances, giving a final $weight_index.
$weight_index = $content_index + $src_index + $alt_index;
return $weight_index;
}
Or would it be more prudent to use the global keyword in front of variables like $content_index, $src_index and $alt_index, and initialize them in a separate file that would be included i.e. init_variables.php that would contain all variables that would need to be initialized before use, as in the examples in this post?
What happens if what you’re looping over happens to be an empty array? Then you wind up with
$arrayor$stringnever being defined, so when something tries to reference it, your program does bad things.