I am trying to pull data out of a foreach loop but I'm running into a strange phenomenon that I haven't encountered yet.
The first row of the CSV looks like this:
Part Number,Description,List Price
Then Data so on and so forth.
What I have:
ini_set('auto_detect_line_endings', TRUE);
if (($openItems = fopen($uploadFile, 'r')) !== FALSE) {
foreach (fgetcsv($openItems) as $key => $value) {
$value = preg_replace('/\h+/', '', strtolower($value));
echo $value;
echo ' = ' . $key . " ";
switch ($value) {
case "partnumber":
$pn = $key;
break;
case "description":
$des = $key;
break;
case "listprice":
$lp = $key;
break;
}
}
print_r("\npn: " . $pn . " des: " . $des . " lp: " . $lp);
}
Print:
partnumber = 0 description = 1 listprice = 2
pn: des: 1 lp: 2
As you can see the first column is falsey so it is not assigned the proper value.
Alternative Print:
test = 0 partnumber = 1 description = 2 listprice = 3
pn: 1 des: 2 lp: 3
I also tried an exercise after $key was echoed that checked:
if($value == 0) {
echo " I'm 0 ";
}
Print:
partnumber = 0 I'm 0. description = 1 I'm 0. listprice = 2 I'm 0.
pn: des: 1 lp: 2
But if you check for numeracy it comes back false:
if(is_numeric($value)) {
echo " I'm a number. ";
}
Print is unchanged:
partnumber = 0 description = 1 listprice = 2
pn: des: 1 lp: 2
That means it is 0 in a NULL or falsey sense right?
if(!$value) {
echo " I'm False or Null. ";
}
But Print is unchanged:
partnumber = 0 description = 1 listprice = 2
pn: des: 1 lp: 2
Type check:
echo "I'm of Type ". gettype($value) . ". ";
returns:
partnumber = 0 I'm of Type string. description = 1 I'm of Type string. listprice = 2 I'm of Type string.
Side Note:
case "partnumber":
$pn = $key;
break;
is never accessed
case "partnumber":
$pn = $key;
echo "I Worked!";
break;
This returns with out any result.
Any, Suggestions?
This Scinario is thanks to @azjezz
$csv = [];
ini_set('auto_detect_line_endings', TRUE);
if (($openItems = fopen($uploadFile, 'r')) !== FALSE) {
foreach (fgetcsv($openItems) as $key => $value) {
$value = preg_replace('/\h+/', '', strtolower($value));
$csv[$value] = (Int) $key;
echo $value;
echo ' = ' . $key . " ";
switch ($csv[$value]) {
case "partnumber":
$pn = $key;
break;
case "description":
$des = $key;
break;
case "listprice":
$lp = $key;
break;
}
}
print_r("\npn: " . $pn . " des: " . $des . " lp: " . $lp);
}
Results in:
partnumber = 0 description = 1 listprice = 2
pn: 0 des: lp:
Another weird scinario:
switch ((int) $value) {
case "partnumber":
$pn = $key;
break;
case "description":
$des = $key;
break;
case "listprice":
$lp = $key;
break;
}
Returns:
partnumber = 0 description = 1 listprice = 2
pn: 2 des: lp: