0

Im trying to sort my database based on extension in laravel, so I try using php pathinfo for it and mix it with looping, yet for some reason the variabel $ext_name didnt output the real extension for the file.

Here is my code:

$i = 0;
            $pdf_file = [];
            $docx_file = [];
            $pdf = 0;
            $docx = 0;
            foreach($files as $i => $the_file){
                $path_name[$i] = $the_file["file_path"];
                $ext_name[$i] = pathinfo($path_name[$i],PATHINFO_EXTENSION);

                if($ext_name[$i]="pdf"){
                    $pdf_file[$pdf]= $the_file["name"];
                }
                elseif($ext_name[$i]="docx"){
                    $docx_file[$docx]= $the_file["name"];
                }

                ++$i;
                ++$pdf;
                ++$docx;

            }

dd result for $path_name and $ext_name:

$path_name

array:5 [▼
  0 => ".........../storage/app/file_processing/blablabla.pdf"
  1 => ".........../storage/app/file_processing/blablabla.docx"
  2 => ".........../storage/app/file_processing/blablabla.pdf"
  3 => ".........../storage/app/file_processing/blablabla.pdf"
  4 => ".........../storage/app/file_processing/blablabla.docx"
]

$ext_name

array:5 [▼
  0 => "pdf"
  1 => "pdf"
  2 => "pdf"
  3 => "pdf"
  4 => "pdf"
]

I dont know how $ext_name output the same extension like that, where exactly that i do something wrong?

2 Answers2

1

You may cleanup your code a bit.

$pdf_file = [];
$docx_file = [];
$ext_name = [];

foreach($files as $key => $file){
  $ext_name[$key] = pathinfo($file["file_path"],PATHINFO_EXTENSION);

  if($ext_name[$key] === "pdf"){
    $pdf_file[$key]= $file["name"];
  } elseif ($ext_name[$key] === "docx"){
    $docx_file[$key]= $file["name"];
  }
}

dd($pdf_file,$docx_file,$ext_name);

You should use == or === instead of =.

Also why this happen? because you assign the pdf to the ext_name[$i] so every iteration of the foreach the ext_name[$i] will ovewrite the pdf extension.

= is an assignment operator and == ond === is an equality operator

Jerson
  • 1,700
  • 2
  • 10
  • 14
0

Try something like:

if ($ext_name[$i] === "pdf") {

OR

if ($ext_name[$i] == "pdf") {

BUT DON'T DO:

if ($ext_name[$i] = "pdf") {

Note that single equal-sign will always just set variable, even if it's written in if-statement.

Same for your other line:

elseif($ext_name[$i]="docx"){
Top-Master
  • 7,611
  • 5
  • 39
  • 71