Skip to content
Advertisement

i want to assign the last element from chars array to the first index of arr array

what is wrong with the for loop logic?

$chars = ["o", "r", "e", "z", "l", "E"];

$count = 0;
$arr = [];

foreach($chars as $values)
{
  while($values != NULL)
  {
    $count ++ ;
    break;
  }
}

for($i = $count; $i > 0; $i--)
{
  for($j = 0; $j < $count; $j++)
  {
    $arr[$j] = $chars[$i];
  }

}

print_r($arr);

i want to assign the last element from chars array to the first index of arr array .

Advertisement

Answer

if you want to invert the array, in your example :

$chars = ["o", "r", "e", "z", "l", "E"];
//Invert index
$arr = ["E", "l", "z", "e", "r", "o"];

you can just use array_reverse() like this :

$arr = array_reverse($chars)

If you still want to create your own loop, you can do something like this :

  $count = count($chars);

  for($j = 0; $j < $count; $j++)
  {
    $arr[$j] = $chars[$count - $j - 1];
  }
10 People found this is helpful
Advertisement