Access array inside a php function - php

Access array with same name $userinfo inside a php function
<?php
$userinfo['name'] = "bob";
$userinfo['lastname'] = "johnson";
function displayinfo() {
//not working
echo $userinfo['name']
//global also not working
echo global $userinfo['lastname'];
}
displayinfo();
?>
how to acess the arrays in the $userinfo var since it has more than one array in the same variable name?
echo $userinfo['name']
//global also not working
echo global $userinfo['lastname'];
both do not working.

I recommend passing the variable to the function:
function displayinfo($userinfo) {
echo $userinfo['name'];
}
$userinfo['name'] = "bob";
$userinfo['lastname'] = "johnson";
displayinfo($userinfo);
See:
PHP global in functions
Are global variables in PHP considered bad practice? If so, why?

try this, for more details PHP Variable Scope
function displayinfo() {
global $userinfo;
echo $userinfo['lastname'];
}
Working example : https://3v4l.org/5l5NZ

Related

PHP variables in function argument is not working

I've retried solving this, by using a condition and a default attribute as recommended.
User-generated data is declared before to $Variable_1:
<?php
$Variable_1 = 'abc123!' //The user inputs the data
if ($booleanvalue == true) { // User selects if they've put data
name($user_data, $Variable_0 = $Variable_1 );
}
//Then the function will use the user's data from $Variable_1
function name($user_data, $Variable_0 = null) {
//Other code...
}
$Variable_2 = name($user_data);
$data['variable_2'] = $Variable_2;
?>
Is it possible to have $Variable_0 pre-declared and then put as an argument?
you have a few mistakes in your code. and I don't think that you can use a function named name.
you could do it this way for example:
<?php
$Variable_1 = 'abc123!';
function test($data) {
global $Variable_1;
//Other calculations...
return $Variable_1 . $data;
}
$testdata = "huhu";
$Variable_2 = test($testdata);
$data['variable_2'] = $Variable_2;
echo $data['variable_2'];
?>
I agree with the comment by El_Vanja, but you can access a global variable through the magic $GLOBALS array anywhere.
<?php
// what you might actually want
function name($variable = 'abc123!')
{
// if no value is passed into the function the default value 'abc123!' is used
}
$variable = 'abc123!';
// what you could do
function name2($variable)
{
// $variable can be any value
// $globalVariable is 'abc123!';
$globalVariable = $GLOBALS['variable'];
}
I'd also like to point out that currently you have no way of controlling what type of data is passed to the function. You might consider adding types.
<?php
<?php
// string means the variable passed to the function has to be a ... well string
function name(string $variable = 'abc123!'): void
{
// void means the function doesn't return any values
}
name(array()); // this throws a TypeError

function parameter as a part of variable name

I was wondering if I can pass function argument as a part of variables name and create new one. Like example below
function do_anything($name) {
global ${$name}_anything;
${$name}_anything = 'hello_world';
}
do_anything('unique');
echo $unique_anything;
Don't tell anyone I wrote this.
<?php
function do_anything($name) {
global ${$name . "_anything"};
${$name . "_anything"} = 'hello_world';
}
do_anything('unique');
echo $unique_anything;

PHP: $_POST variables unexistant into functions

I am bringing some info trough $_POST, but when I try to make use of this info into any function, console emerges an error about Undefined Variable (in this example, $ms_img brings an error, as well as $con -the connection query declared on conexionbbdd.php- and any othe variable inside functions.
EDIT: Neither passing as arguments works, it emerges one error per argument as this:
Warning: Missing argument 1 for checkCost(), called in C:\wamp\www...\actions\msg_newMessage.php on line 96 and defined in C:\wamp\www...\actions\msg_newMessage.php on line 17
function checkCost($con,$ms_img,$id){...}
CODE:
<?php
session_start();
include("../conexionbbdd.php");
include("../conexionapi.php");
$id = $_SESSION['id'];
$inclass = $_SESSION['inclass'];
if($_SESSION['estado'] == 'activo'){
$ms_content = $_POST['ms_content'];
$ms_img = $_POST['ms_img'];
$ms_prefix = $_POST['ms_prefix'];
$ms_phone = $_POST['ms_phone'];
function checkCost(){
$totalCost = 0;
if ($ms_img!=""){
$totalCost=2;
}
else{
$totalCost=1;
}
$checkCredits=mysqli_query($con,"SELECT us_credits FROM ws_users WHERE us_id=$id");
}
function sendMessage(){
//WHATEVER
}
if($inclass==='1'){
checkCost();
}
else{
sendMessage();
}
}else{
header('location:../login.php');
}
?>
You can have access to superglobal variables like $_POST in any function. But global variables such as $con that should be initialized in an including file is not accessable in a function. You can pass it as parameter. And do not use the global keyword to inject global vars into a funciton. In long term this can result very confusing code. So you could do:
function checkCost($con){
$ms_content = $_POST['ms_content'];
$ms_img = $_POST['ms_img'];
$ms_prefix = $_POST['ms_prefix'];
$ms_phone = $_POST['ms_phone'];
$totalCost = 0;
if ($ms_img!=""){
$totalCost=2;
}
else{
$totalCost=1;
}
$checkCredits=mysqli_query($con,"SELECT us_credits FROM ws_users WHERE us_id=$id");
}
But its still very procedural. I recommend you to start to read OOP.

Unable To Access PHP Global Variable

I am trying to pull global variable $nsfw but it shows nothing at all. If I echo it inside function, it works. But outside, it fails even when defined as global. Kindly help me out here.
<?php
if(!function_exists('do_example_work'))
{
function do_example_work()
{
global $nsfw;
include("includes/dbconnect.php");
// Create connection
$conn = new mysqli($DBHOST, $DBUSER, $DBPASS, $DBNAME);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT fieldname FROM table WHERE name='$anything'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
if ($row["fieldname"] == 1) {
// do somethin
$nsfw = 25;
exit();
} else {
echo "enjoy";
}
}
} else {
echo "0 results";
}
}
echo $nsfw;
};
?>
There are arguments for and against Globals. You can search Stack and the internet and read about:
Globals are bad in many ways, and should be avoided where possible
Globals are not bad, and can be fine/safe to use if you know what you are
doing
The manual:
http://php.net/manual/en/functions.user-defined.php
You seem to be over complicating things with this basic user defined function.
OUT
If you want to get data out of a function, just use the return statement
function do_example_work() {
// Do some stuff here
$nsfw = 25;
return $nsfw; // Return where needed, in conditional statement or end of function
}
// Will echo "25"
echo do_example_work();
IN
FYI:
To get data into the function from outside, just pass the data into your function from the outside as an argument:
function do_example_work($nsfw) {
/** The var "$nsfw" will have whatever data you pass in through the function call
* You can use it as required - check if $nsfw == something
* Or it might be database login details (urgh)
*/
echo $nsfw." - And words from in the function";
}
// Will echo "Pass in argument - And words from in the function"
do_example_work("Pass in argument");
The keyword global in front of a variable name means that the variable is defined somewhere outside the function, and now I want to use that variable. It does not generate a global variable. So you need to define the variable outside the function, and then you can use that variable inside a function using the global keyword in front of it.
In your code I cannot see you defining the variable outside the function. You are just echoing it out at the bottom of your code.
Any specific reason for keeping global variable inside method ?? Move it outside method and it should work for u.
Or
Try GLOBALS as shown below.
function doit() { $GLOBALS['val'] = 'bar'; } doit(); echo $val;
Gives the output as :
bar
Or
<?php
foo();
bar();
function foo() { global $jabberwocky; $jabberwocky="test data<br>"; bar(); } function bar() { global $jabberwocky; echo $jabberwocky; } ?>

PHP getter method question

Hi Im new to PHP so forgive the basic nature of this question.
I have a class: "CustomerInfo.php" which Im including in another class. Then I am trying to set a variable of CustomerInfo object with the defined setter method and Im trying to echo that variable using the getter method. Problem is the getter is not working. But if I directly access the variable I can echo the value. Im confused....
<?php
class CustomerInfo
{
public $cust_AptNum;
public function _construct()
{
echo"Creating new CustomerInfo instance<br/>";
$this->cust_AptNum = "";
}
public function setAptNum($apt_num)
{
$this->cust_AptNum = $apt_num;
}
public function getAptNum()
{
return $this->cust_AptNum;
}
}
?>
<?php
include ('CustomerInfo.php');
$CustomerInfoObj = new CustomerInfo();
$CustomerInfoObj->setAptNum("22");
//The line below doesn't output anything
echo "CustomerAptNo = $CustomerInfoObj->getAptNum()<br/>";
//This line outputs the value that was set
echo "CustomerAptNo = $CustomerInfoObj->cust_AptNum<br/>";
?>
Try
echo 'CustomerAptNo = ' . $CustomerInfoObj->getAptNum() . '<br/>';
Or you will need to place the method call with in a "Complex (curly) syntax"
echo "CustomerAptNo = {$CustomerInfoObj->getAptNum()} <br/>";
As your calling a method, not a variable with in double quotes.
for concat string and variables, you can use sprintf method for better perfomace of you app
instead of this:
echo "CustomerAptNo = $CustomerInfoObj->getAptNum()<br/>";
do this:
echo sprintf("CustomerAptNo = %s <br />", $CustomerInfoObj->getAptNum());
check http://php.net/sprintf for more details

Categories