Home > database >  PHP Undefined offset: 0 while doing string append
PHP Undefined offset: 0 while doing string append

Time:12-02

Hi I am trying to get this string i.e "C:/xampp/htdocs" , to a separate array which is $url[] in a way that it stores like this

$url[0]  ---- > C:/
$url[1]  ---- > C:/xampp
$url[2]  ---- > C:/xampp/htdocs

NO matter how big the string is I should be store like this , which I did but I am getting this error below .

can anyone please tell why am I getting this error ?

<?php
$directory="C:/xampp/htdocs";

//coverting the string into an array
$arr=explode('/',$directory);

//store the count of the array in $n for looping
$n=count($arr);

//declaring an empty array
$url=[];

$k=0;
for($i=0;$i<$n;$i  ){
    for($j=0;$j<=$i;$j  ) {
        $url[$k].=$arr[$j].'/';
    }
    $k  ;
    echo "<br>";
}
echo "<br>";

print_r($url);


?>

The data store in $url array that I am printing with print_r() function is as the way I wanted but can't figured why the error is occurring , anyone has solution?

output is here

CodePudding user response:

$url=[] just declares an empty array, so that when:

   $url[$k].=$arr[$j].'/';

is first executed, it is read as:

   $url[0]=$url[0].$arr[$j].'/';

and $url[0] isn't defined.

Use array_fill() to populate the array instead:

$url=array_fill(0,$n,'');

So the whole code looks like (I've added an extra directory to show why array_fill is necessary):

<?php
$directory="C:/xampp/htdocs/samples";
$arr=explode('/',$directory);
$n=count($arr);
$url=array_fill(0,$n,'');
$k=0;
for($i=0;$i<$n;$i  ){
    for($j=0;$j<=$i;$j  ) {
        $url[$k].=$arr[$j].'/';
    }
    $k  ;
}
print_r($url);
?>

Output:

Array
(
    [0] => C:/
    [1] => C:/xampp/
    [2] => C:/xampp/htdocs/
    [3] => C:/xampp/htdocs/samples/
)

Teh Playground!

CodePudding user response:

If you don't mind modifying the original array you could simply append the current value to the previous one.

$directory = "C:/xampp/htdocs";
$url = explode('/', $directory);

foreach ($url as $i => $value) {
  if ($i > 0) {
    $url[$i] = $url[$i-1] . '/' . $value;
  }
}
// first index is the only one with trailing slash
$url[0] .= '/';
  •  Tags:  
  • php
  • Related