W3docs

Changing a global variable from inside a function PHP

In PHP, global variables can be accessed and modified from within functions using the global keyword.

In PHP, global variables can be accessed and modified from within functions using the global keyword. For example, to access a global variable called $x from within a function, you would use the following code:

Example of accessing a global variable from within a function in PHP

<?php

$x = 10;

function modify_global()
{
  global $x;
  $x = 20;
}

modify_global();
echo $x; // outputs 20

<div class="alert alert-info flex not-prose"> Watch a course <span class="hidden md:block">Watch a video course </span> Learn object oriented PHP</div>

This will change the value of the global variable $x to 20 within the function. Alternatively, you can use the $GLOBALS superglobal array to access and modify global variables directly. Keep in mind that using global variables can make code harder to understand and maintain, and it is often better to pass variables as function arguments or use an object-oriented design.