Can I not do this?
$png = array();
$jpeg = array();
$jpg = array();
$gif = array();
if($dirOpen = opendir('imagefiles'))
{
while(($imagee = readdir($dirOpen))!==false)
{
if ($imagee == '.' or $imagee == '..') continue;
echo var_dump($imagee);
switch($imagee)
{
case "%.png": $png[] = $imagee; break;
case "%.jpeg": $jpeg[] = $imagee; break;
case "%.jpg": $jpg[] = $imagee; break;
case "%.gif": $gif[] = $imagee; break;
default: echo "error";
}
}
print_r($jpg);
closedir($dirOpen);
}
$imagesss = array_merge($png, $jpeg, $jpg, $gif);
I'm trying to sort the images by type, so if I get something like KJFEORHGkjheilg.jpg then it goes to case '%.jpg', but apparently not. why?
CodePudding user response:
You are using an operator inside a string, you cannot do comparisons inside a case .. case IS the comparison .. And you're using a division operator %
as a wildcard at that .. I would (assuming you only had one .
in your file name) do something like this using explode
:
switch( explode('.', $imagee)[1] )
{
case "png": $png[] = $imagee; break;
case "jpeg": $jpeg[] = $imagee; break;
case "jpg": $jpg[] = $imagee; break;
case "gif": $gif[] = $imagee; break;
default: echo "error";
}
Explained:
explode('.', 'imagename.png')
will create an array
[0]imagename
[1]png
So explode('.', 'imagename.png')[1]
will be png
UPDATE
If you had more than 1 .
in your file name .. you could do a little logic before hand.
$im_length = ( count( explode('.', $imagee) ) - 1);
$imagee = explode('.', $imagee)[$im_length];
switch( $imagee )
{
case "png": $png[] = $imagee; break;
case "jpeg": $jpeg[] = $imagee; break;
case "jpg": $jpg[] = $imagee; break;
case "gif": $gif[] = $imagee; break;
default: echo "error";
}
CodePudding user response:
No, you cannot use %
as a wildcard in switch
case, nor is there any other wildcard. Just get the extension and use that in the switch
cases. For instance with pathinfo().
Here's your code using that:
$png = [];
$jpeg = [];
$jpg = [];
$gif = [];
if ($dirHandle = opendir('imagefiles')) {
while (($filename = readdir($dirHandle))) {
switch (strtolower(pathinfo($filename, PATHINFO_EXTENSION))) {
case "png" : $png[] = $filename; break;
case "jpeg" : $jpeg[] = $filename; break;
case "jpg" : $jpg[] = $filename; break;
case "gif" : $gif[] = $filename; break;
}
}
closedir($dirHandle);
}
$imageFiles = array_merge($png, $jpeg, $jpg, $gif);
Since you merge the images file all together at the end you could also do:
$imageTypes = ["png", "jpeg", "jpg", "gif"];
$imageFiles = [];
if ($dirHandle = opendir('imagefiles')) {
while (($filename = readdir($dirHandle))) {
$extension = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
if (in_array($extension, $imageTypes)) {
$imageFiles[] = $filename;
}
}
closedir($dirHandle);
}