PHP Compact() function returning a empty array - php

I have a array containing to which I have created local variables from using the extract() function with the EXTR_PREFIX_ALL flag set. Afterwards, I called compact() on the new prefixed variables created by extract() but displaying the array created from compact() using print_r() gives an empty array(). Sample code follows:
<?php
$cities = array('City1' => "Chicago", 'City2' => "Boston");
extract($cities, EXTR_PREFIX_ALL, "new");
echo "City 1: {$new_City1} City 2: {$new_City2}" . "<br><br>";
$new_cities = compact($new_City1, $new_City2);
print_r($new_cities);
?>
I am using PHP version 5.6. What am I doing wrong here?

In your current code, you're actually providing the values of each variables you're trying to compact, not the name of the variables. It acts like a variable variables behavior. In order to make it work properly, you provide the variable names as strings or in array form:
$new_cities = compact(array('new_City1', 'new_City2'));
// or
$new_cities = compact('new_City1', 'new_City2');
Here's the excerpt from the manual:
Parameters
varname1
compact() takes a variable number of parameters. Each parameter can be either a string containing the name of the variable, or an array of variable names. The array can contain other arrays of variable names inside it; compact() handles it recursively.

Give it a try
$new_cities = compact('new_City1', 'new_City2');
print_r($new_cities);
For more info

Related

Get a value from an associative array with $_GET

Say for example that I have this variable
$p0001 = array("title"=>"This is the title","name"=>"Just Me");
And the URL is
https://www.example.com?id=p0001
How do I get the correct array from PHP? I've tried
echo $_GET["id"]["title"];
To explain little more, say I have two array variables. I want it to echo the "title" from from the array $p0001. So how do I make sure I gets the variable I put in $_GET?
You can use Variable variables
So, your variable name is $p0001. Your GET parameter id is basically a pointer to the variable name, so using variable variables, we can reference the variable we're looking for:
$varname = $_GET['id']; // $varname = 'p0001';
$$varname; // this is basically $p0001
$$varname['title']; // and you can get your title from $p0001
You could also check if a variable exists before using with isset($$varname)

PHP Value from Array

I'm trying to work out how to get values from one of three arrays based on the array name.
$ABC001 = array('A'=>'10','B'=>'2','C'=>'1.0');
$ABC002 = array('A'=>'20','B'=>'4','C'=>'1.1');
$ABC003 = array('A'=>'30','B'=>'6','C'=>'1.2');
I have a variable passed to my script it will be contain something like ABC#001 or ABC#002
I'm removing the # so the var value now matches the array name/
$test = str_replace('#','',$var);
If I do var_dump ( $$test ) I get all the values from the correct array, but if I do echo $$test['A'] or echo $$test[0] I don't get the value from the first key in the correct array.
Can someone advise how to do this.
Thanks
try this ${$test} to get the values of the array
<?php
$ABC001 = array('A'=>'10','B'=>'2','C'=>'1.0');
$ABC002 = array('A'=>'20','B'=>'4','C'=>'1.1');
$ABC003 = array('A'=>'30','B'=>'6','C'=>'1.2');
$var = "ABC#002";
$test = str_replace('#','',$var);
var_dump(${$test}['A']);
In order to use variable variables with arrays, you have to resolve an ambiguity problem. That is, if you write $$test['A'] then the parser needs to know if you meant to use $test['A'] as a variable, The syntax for resolving this ambiguity is: ${$test}['A'] . Please check the documention here PHP Variable Variable

Are arrays passed by reference or value in PHP?

Are arrays passed by reference or value in PHP?
For example, let's see this code.
function addWeight($arout, $lineCountry, $lineDomain, $target, $weight)
{
$currentDomain=getDomain();
$currentCountry=getCountry();
if ($currentCountry==$lineCountry && ($currentDomain == $lineDomain || $lineDomain==""))
{
$tarobreakpoint=0;
$arout [$target] = intval($weight);
}
return $arout;
}
Basically it took an array as a parameter. Depending on some circumstances it adds elements to the array. I wonder if this is efficient? If $arout is passed by reference like all arrays should then I think it's efficient. But if it's just copied and passed by value then well it's not.
So what's the verdict?
According to the manual, PHP arrays are passed by value:
Array assignment always involves value copying. Use the reference operator to copy an array by reference.
If you'd like to pass an array's reference, use the corresponding operator (&) as mentioned above, and remove the return $arout; line in the addWeight() function:
<?php
// pass $array by reference using & operator
addWeight(&$array, $lineCountry, $lineDomain, $target, $weight);

php numeric Variable Name

I want to append some $variables automaticly and set their names numeric
I have a script look like this:
<?php
$i=0;
while($i<=100){
$variable_[$i]=$i;
$i++;
#with "[$i]" I mean their name will be $variable_1 , $variable_2, $variable_3 ...
#they will be automatic increased variables non manual!
}
?>
This is called variable variables.
You can set a variable variable by defining its name inside a variable, such as:
$name = 'variable_' . $i;
and then assign a value to it by doing:
$$name = $i;
Note that variable variables can easily be misused. Make sure you completely understand the repercussions of this feature on your code and the risk of having bugs, and ensure this is the only solution you have, i.e. you can't use an array ($variables[$i] = $i;) instead.
Its better to use Array with key=> value pair. You can build this array dynamically and then loop through it by using foreach.

PHP extract values from an array and pass them to a function

I'm trying to extract values from an array, and pass them to a function where they'll be used. I've used echo inside the function for this example.
I'm using extract to get all the values.
Thing is, this wont work. Do you see how this can be done?
<?php
$my_array = array("a" => "Prince", "b" => "Funky"); // around 10 more
$g = extract($my_array);
foo($g);
function foo($g) {
echo 'My name is '.$a.', and I am '.$b;
}
?>
Functions in PHP have a different scope, so the variables $a, $b etc. aren't available inside your function. Trying to use them inside the function would result in Undefined variable notices (if you enable error reporting, that is).
Right now, you're storing the return value of extract() (which is the total number of variables parsed) into your function. You want the values instead, so change your function like so:
function foo($array) {
extract($array);
echo 'My name is '.$a.', and I am '.$b;
}
Note that I've moved the extract() call inside the function. This way, you wouldn't pollute the global scope with random variables (which may have undesired results and will make your debugging hard for no reason).
Now you can call your function, like so:
foo($my_array);
Output:
My name is Prince, and I am Funky
Demo
It's better to avoid extract() altogether, though. See: What is so wrong with extract()?
You can pass your array in your function as you do with any other variable
$my_array = array("a" => "Prince", "b" => "Funky"); // around 10 more
foo($my_array);
function foo($arrayData)
{
echo 'My name is '.$arrayData['a'].', and I am '.$arrayData['b'];
}

Categories