How to set array's two keys with same value? (PHP) - php

There exists such:
$var1 = $var2 = "blabla";
but is there a way to set similar inside array? like:
array(
'key1'='key2' => "blabla",
...................
)
p.s. I dont need outside of array functions, like array_fill_keys or etc.. I want inside-array solution (if it exists).

You can set multiple array values of an array like this. Perhaps it even works without the first line.
$a = array();
$a['key1'] = $a['key2'] = 'blablabla';
Or initialize the desired keys using this awkward syntax:
$a = array_fill_keys(array('key1', 'key2'), 'blablabla');
Although the second one works, I wouldn't use it. Better to use a couple of characters extra or even separate lines than to write such a weird line which doesn't have much benefit apart from saving a tiny bit of code.

Related

Shorten multimensional array reference?

I want to output some information to an array from a multidimensional one referenced like this:
$adam_brown[$climbing][$punk]['woodwork'][1]['ID']
$adam_brown[$climbing][$punk]['cheese'][1]['Name']
$adam_brown[$climbing][$punk]['ruffian'][1]['ID']
This part will always be the same, so could I create a shorter, maybe one letter reference to it, e.g.:
$a = $adam_brown[$climbing][$punk]
Otherwise I am needlessly writing the same information several times
Then I could reference the above info like this:
$a['woodwork'][1]['ID']
If you want to make a shorthand to the $adam_brown[$climbing][$punk], just do it as you wrote:
$a = $adam_brown[$climbing][$punk];
However if you want to be able to modify the original array, you have tu use & reference:
$a = &$adam_brown[$climbing][$punk];
Documentation: Returning References
Simply use
$a = &$adam_brown[$climbing][$punk];

php get array elememnt using $$

i know this
$var1 = "10";
$var2 = "var1";
then
echo $$var2 gives us 10
i want to this with array
i have array
$intake_arr = array(5=>10,7=>20,8=>30,9=>40,10=>50,11=>60,12=>70);
i have some logic that will pick one array from set of array , all array will look like $intake_arr
if i do this $target_arr = "intake_arr";
then can $$target_arr[5] will yield 10? i tried but i didnt that 10 value, how can i achieve this with array
Your statement ($$target_arr[5]) is ambiguous. PHP doesn't know what you actually want to say: Do you mean: use $target_arr[5]'s value and prepend the $, to use that as a variable, or do you want to use the value of $target_arr, and get the fifth element of that array?
Obviously it's the latter, but PHP doesn't know that. In order to disambiguate your statement, you have to use curly braces:
${$target_arr}[5];
That'll yield 10. See the manual on variable variables for details
Note:
As people said in comments, and deleted answers: variable variables, like the one you're using is risky business. 9/10 it can, and indeed should be avoided. It makes your code harder to read, more error prone and, in combination with the those two major disadvantages, this is the killer: it makes your code incredibly hard to debug.
If this is just a technical exercise, consider this note a piece of friendly advice. If you've gotten this from some sort of tutorial/blog or other type of online resource: never visit that site again.
If you're actually working on a piece of code, and you've decided to tackle a specific problem using variable vars, then perhaps post your code on code-review, and let me know, I'll have a look and try to offer some constructive criticism to help you on your way, towards a better solution.
Since what you're actually trying to do is copying an array into another variable, then that's quite easy. PHP offers a variety of ways to do that:
Copy by assignment:
PHP copies arrays on assignment, by default, so that means that:
$someArray = range(1,10);//[1,2,3,4,5,6,7,8,9,10]
$foo = $someArray;
Assigns a copy of $someArray to the variable $foo:
echo $foo[0], ' === ', $someArray[0];//echoes 1 === 1
$foo[0] += 123;
echo $foo[0], ' != ', $someArray[0];//echoes 123 != 1
I can change the value of one of the array's elements without that affecting the original array, because it was copied.
There is a risk to this, as you start working with JSON encoded data, chances are that you'll end up with something like:
$obj = json_decode($string);
echo get_class($obj));//echoes stdClass, you have an object
Objects are, by default, passed and assigned by reference, which means that:
$obj = new stdClass;
$obj->some_property = 'foobar';
$foo = $obj;
$foo->some_property .= '2';
echo $obj->some_property;//echoes foobar2!
Change a property through $foo, and the $obj object will change, too. Simply because they both reference exactly the same object.
Slice the array:
A more common way for front-end developers (mainly, I think, stemming from a JS habbit) is to use array_slice, which guarantees to return a copy of the array. with the added perk that you can specify how many of the elements you'll be needing in your copy:
$someArray = range(1,100);//"large" array
$foo = array_slice($someArray, 0);//copy from index 0 to the end
$bar = array_slice($someArray, -10);//copy last 10 elements
$chunk = array_slice($someArray, 20, 4);//start at index 20, copy 4 elements
If you don't want to copy the array, but rather extract a section out of the original you can splice the array (as in split + slice):
$extract = array_splice($someArray, 0, 10);
echo count($someArray);//echoes 90
This removes the first 10 elements from the original array, and assigns them to $extract
Spend some time browsing the countless (well, about a hundred) array functions PHP offers.
${$target_arr}[5]
PHP: Variable variables
Try this one:
$intake_arr = array(5=>10,7=>20,8=>30,9=>40,10=>50,11=>60,12=>70);
$target_arr = 'intake_arr';
print ${$target_arr}[5]; //it gives 10
For a simple variable, braces are optional.But when you will use a array element, you must use braces; e.g.: ${$target_arr}[5];.As a standard, braces are used if variable interpolation is used, instead of concatenation.Generally variable interpolation is slow, but concatenation may also be slower if you have too many variables to concatenate.Take a look here for php variable variables http://php.net/manual/en/language.variables.variable.php

Javascript variable initialization

There, an odd thing just happened..
Normally I assign my global variables like this:
orders = [];
pOrders = [];
But I was lazy and just wrote:
orders = pOrders = [];
It should mean the same, shouldn't it??
Apparently not because the array pOrder also contained the array orders data. I sat for 15 min looking for a bug in my code but couldn't find any so I just tried writing the variables as I normally would and it worked. Why does this happen?
In PHP, the logic would be the same, but JavaScript seems to behave differently.
Please could anyone provide me with some information, or knowledge..
In the second example, you're explicitly assigning the exact same array instance to two separate variables. There's only one array involved, while in the first case there are two.
I would be somewhat surprised to learn that PHP really would treat those two pieces of code as meaning the same thing.
That code you wrote there last is the same as:
orders = [];
pOrders = orders;
So now you have two variables which are references to the same array. That's why you are exeriencing this behavior.
When instead you do it as you did in your first example:
orders = [];
pOrders = [];
Then you have two completely separate and distinct arrays.
You assigned both variables to refer to the same array instance.
To see what everyone means by "same array instance", run the following JavaScript in your browser:
orders = pOrders = [];
orders.push("hello");
pOrders.push("world");
console.log(orders);
console.log(pOrders);
Check the console output, both messages will say ["hello", "world"].

How to assign PHP-variables by using two arrays

I'm trying to use a for-loop which loops through two arrays.
My first one looks like this:
$pos = array("Yada Yada", "Boom Boom");
And the second one looks like this:
$pos_var_names = array("yada", "boom");
My goal is to use a for-loop to automatically loop through both arrays at the same time and for example set:
$yada = "Yada Yada";
How do I do this in the most efficient way?
Sorry if I'm missing something obvious. Have been coding for a couple of hours straight and I'm feeling a bit dizzy.
Best regards!
You could use a for-loop:
for ($i = 0; $i < count($pos); $i++)
${$pos_var_names[$i]} = $pos[$i]; // variable variables
But it is more elegant like this:
extract(array_combine($pos_var_names, $pos));
This just makes an $varname => $pos array (see also the documentation for array_combine which is then extract()'ed.
But generally, it's better to just have an associative array instead of using tons of variables. It just will fill your variable scope with useless variables which might conflict with other variables you have.

Declaring static arrays in php

I am new to php. I was wondering how I could declare a static array in php. Here is what I would do in C. How is the corresponding php code for it?
char a[][] = { (1,1), (1,2), (1,3), (2,1), (2,2), (2,3), (3,1), (3,2), (3,3) };
From what I read it has to be something like this -
$a = array( 1 => array(1,1), 2 => array(1,2), ... );
Is this correct? If so it sucks :) I hope I am wrong.
Thanks,
- Pav
You've already found the way to do it natively.
Another option would be to declare your data as JSON (a very concise and human-friendly format). This could be either in a separate file bundled with your app, or directly in your code in a string. Then parse the JSON at runtime. Since PHP isn't exactly known for speed, this may or may not make your noticeably app slower to start.
you have it already figured out in your question.
One thing I would add is that you do not need to explicitly define the keys if you are intending to use a zero based array, this is assumed and can be done like so...
$a = array(array(1,1),array(1,2), ... );
You can also use what is called associative arrays which use string keys and you define them the same way you do in your example, except use strings instead of numbers...
$ass_array = array( 'array_1' => array(1,1), 'array_2' => array(1,2), ... );
you would then call your associative array like this...
$ass_array['array_1'];
Also, if you want to append single items to an array (for example in a loop to load an array)...
$ass_array[] = $item;
Further to jondavidjohn's anwser, you could just write a quick script to grab your list of values and generate the array statement for you.
No need to care how verbose the syntax is then. If the task is long and repetitious enough to care, don't do it by hand. :)

Categories