Variable array names - php

Fatal error: Cannot use string offset as an array
This appears when I try to find a array key by using variable array name:
class FOO {
protected $arr = array();
function bar(){
$aaaaaaaaaaaa = 'arr';
$this->$aaaaaaaaaaaa[$somekey]; // <-- error
...
}
}
How can I do this with variable array names?

#MarcinJuraszek's right, when you assign $arr the second time it's no longer an array.
Anyway, I believe this code does what you intend to
<?php
class foo
{
public function doStuff()
{
$name = 'arr';
$this->{$name} = array('Hello world!');
echo $this->{$name}[0];
}
}
$obj = new foo;
$obj->doStuff();

After that part of code:
$arr = 'arr';
$arr is no more an array. It's just a variable containing 'arr' string. So you can't access it as by key.
You should read information from PHP: Arrays - Manual.

$this->{$arr}[$somekey]
is what you want (provided that you actually assign array to $this->arr, not just $arr that you reassign later.

$arr is not an array. You first created one but then it's getting a string variable here: $arr = 'arr';.
This is correct:
$arr = array();
$arr[] = 'arr';
$somekey = 0;
$this->$arr[$somekey]

you are first defining $arr as an array, then you are OVER-writing its definition with a string. instead, maybe you wanted to add an element to the list:
$arr = array();
$somekey = 'mykey';
$arr[$somekey] = 'arrVal';
echo $arr[$somekey]
i think, i know what you want now:
a list of arrays...
$arr = array():
$arr['aaaaaaaaaa'] = array();
$arr['aaaaaaaaaa'][$somekey] = 'arrVal';
echo $arr['aaaaaaaaaaa'][$somekey]
and what's up with all the screaming?

After say
$arr = 'arr';
Variable $arr is no longer a variable, may be what you want to do is add that value to the array in which case try the following:
arr.push('arr');
Then it should work I think

Related

php to create an array with value stored in variables

well, i have 2 variables
$variable1 = "123";
$variable2 = "321";
both variables are calculated by other methods and may vary due to change of circumstances, now i want to put these values in a single array for displaying, what i want is something like this
$array = ($variable1, $variable2)
and print like(in IDE)
array([0]=>123 [1]=>321)
both 123 and 321 are representations of variable values.
i tried compact() function but it gave me something weird, i tried make these two variables an array with only one element and merge them into one array but in fact i have many variables and it's infeasible to do this for every one of them.....please show me how i can do it and explain in detail the mechanism behind it, thank you very much.
There are several ways to do what you want.
You can use one of examples below :
// Define a new array with the values
$array1 = array($variable1, $variable2);
// Or
$array2 = [$variable1, $variable2];
// Debug
print_r($array1);
print_r($array2);
// Define an array and add the values next
$array3 = array();
$array3[] = $variable1;
$array3[] = $variable2;
// Debug
print_r($array3);
// Define an array and push the values next
// http://php.net/manual/en/function.array-push.php
$array4 = array();
array_push($array4, $variable1);
array_push($array4, $variable2);
// Debug
print_r($array4);
Just use the array function to get the values into one array.
$var1 = "123";
$var2 = "321";
$array = array($var1,$var2);
var_dump($array); returns:
array (size=2)
0 => string '123' (length=3)
1 => string '321' (length=3)
Or another example on how you could do it is:
$array = array();
$array[] = myFunction(); //myFunction returns a value and by using $array[] you can add the value to the array.
$array[] = myFunction2();
var_dump($array);
Here is your answer
$variable1 = "123";
$variable2 = "321";
$arr =array();
array_push($arr,$variable1);
array_push($arr,$variable2);
echo '<pre>';
print_r($arr);
Hope this will solve your problem.
As you want to put these item in array
First you have to initialize a variable
$newArray = []
After that you have to store the value in array which can be done by this
$newArray[] = $variable1;
// OR BY
array_push($newArray, $variable1);
They both are same it push the data to the end of the array
So your code will be like this
$newArray = []
$newArray[] = $variable1;
$newArray[] = $variable2;
If you want to do it in loop then do somthing like this
$newArray = []
foreach($values as $value){
$newArray[] = $value;
}
If there is a fix value then you can do like this
$newArray = [$variable1, $variable2];
//OR BY
$newArray = array($variable1, $variable2);
Both are same
And to print the value use
print_r($newArray);
Hope this will help

How to use string values from one array as indexes for another array in PHP

I've splitted a string into array, giving a delimitator. So, this new array created, will contain values that I would want to use as indexes for another given array.
Having a situation like this:
// my given array
$array['key1']['key2']['a_given_key']['some_other_given_key'] = 'blablabl';
// the value of my given array
$value = $array['key1']['key2']['a_given_key']['some_other_given_key'];
$string = "key1;key2";
$keys = explode(";", $string);
I want to call dinamically (during the execution of my PHP script) the value of the given array, but, using as indexes all the values of the array $keys, and in addition appending the indexes ['a_given_key']['some_other_given_key'] of my given array.
I hope I have been clear.
Many thanks.
To make it work you have to use references. Below code should work as you expect:
<?php
$string = "key1;key2;key3;key4";
$keys = explode(";", $string);
$array['key1']['key2']['key3']['key4']['a_given_key']['some_other_given_key'] = 'blablabl';
$ref = & $array;
for ($i=0, $c = count($keys); $i<$c ; ++$i) {
$ref = &$ref[$keys[$i]];
}
echo $ref['a_given_key']['some_other_given_key'];
$value = $ref['a_given_key']['some_other_given_key'];
echo $value;
?>
I would like to add that just after using reference you should unset it using:
unset($ref);
If you don't do this and many lines later you run for example $ref = 2; it will modify your source array so you have to remember about unsetting references just after it's no longer in use.

changing a php variable name throughout for loop

I have an array that I want to rename so that the values are stored depending on what number the for loop is on. I tried something like this but its giving me an error.
for ($i =0;$i<4;$i++){
$array.$i = array();
push stuff into array;
}
So at the next iteration the array is called array1, then array2 and so forth. What is the best way to do this.
To literally answer your question:
$arrayName = 'array' . $i;
$$arrayName = array();
$$arrayName[] = ...
What you really want is a multidimensional array though:
$array[$i] = array();
$array[$i][] = ...;
You want to use variable variables, in which the double dollar sign indicates that the name of the variable is taken from a variable.
$varname = "array";
for ($i =0;$i<4;$i++){
$newvarname = $varname . $i
$$newvarname = new array()
push stuff into array;
}
I would add that in these cases, a simpler solution is often to use an array in which the desired variable names are indices. So instead of creating $array1, $array2, and so forth, you'd have:
$arrays = array (
'array1' => array(stuff),
'array2' => array(stuff),
'array3' => array(stuff),
'array4' => array(stuff)
}
At least, I find it easier to keep track of.
You should be able to reference the array using the $$ notation for variable variables (see: http://www.php.net/manual/en/language.variables.variable.php).
So, something like this should work (untested):
for ($i =0;$i<4;$i++){
$thisArrayName = 'array'.$i;
$$thisArrayName = array();
push stuff into array;
}
You need array of array
for ($i =0;$i<4;$i++){
$array[$i] = array();
push stuff into array;
}

call_user_func_array + array_intersect with an array of array names, possible?

Sorry for the confusing title...
I need to perform an array_intersect() against a variable number of arrays. To do this it seems I need to use the call_user_func_array() function, however, this doesn't seem to be working and gives me the error:
Warning: array_intersect() [function.array-intersect]: Argument #1 is not an array in...
But, if I "print_r" the array to make sure then I see that it is an array:
Array ( [0] => arr_0 [1] => arr_1 )
My code (trimmed to just show the broken part):
$i = 0;
$arr_results = array();
foreach($arr_words as $word) {
$arrayname = "arr_".$i;
$$arrayname = array();
while ($row = mysql_fetch_assoc($search)) {
array_push($$arrayname, $row['id']);
}
array_push($arr_results, "$arrayname");
$i++
}
$matches = call_user_func_array('array_intersect',$arr_results);
In the full code I'm populating the arrays in the foreach loop with data obtained from sql queries.
From my comments:
"$arrayname" is a string, not an array. call_user_func_array will pass each element in $arr_results as argument to array_intersect. array_intersect expects arrays as arguments, but each item in $arr_results is a string, not an array.
All you have to do is create an array of arrays instead of array names:
$arr_results = array();
foreach($arr_words as $word) {
$ids = array();
while ($row = mysql_fetch_assoc($search)) {
$ids[] = $row['id'];
}
$arr_results[] = $ids;
}
$matches = call_user_func_array('array_intersect',$arr_results);
I turn $arrayname into an array with $$arrayname = array();
Right, you create a variable, lets say arr_0 which will point to array. But there is still a difference between the variable name arr_0 and the string containing the variable name "arr_0". You create an array of strings, and that just won't work. PHP does not know that the string contains a name of a variable. For example, consider this:
$arr = "arr_0";
echo $arr[0];
Based on your logic, it should output the first element of the array, but it does not, because $arr is a string, not an array, although it contains the name of a variable.
You'd have to use eval, but you really should not. You could also use variable variables again:
array_push($arr_results, $$arrayname);
that would work as well, but as I said, variable variables are confusing and in 99% of the cases, you are better of with an array.

"Classic" array in php

So, I'm starting a new project and working with php for the first time.
I get that the average definition and functioning of arrays in php is actually pretty much a namevalue combo.
Is there some syntax, API, or other terminology for just a simple list of items?
I.e. inserting something like ['example','example2','example3','example4'] that I can just call based off their index position of the array, without having to go in and modify the syntax to include 0 => 'example', etc...
This is a very shortlived array so im not worried about long term accessibility
php arrays are simple to use. You can insert into an array like:
$array=array('a','b','c'.....);
Or
$array[]="a";
$array[]="b";
$array[]="c";
or
array_push($array, "a");
array_push($array, "b");
array_push($array, "c");
array_push($array, "d");
and call them by their index values:
$array[0];
this will give you a
$yourArray = array('a','b','c');
or
$yourArray[] = 'a';
$yourArray[] = 'b';
$yourArray[] = 'c';
will get you an array with integer index values instead of an associative one..
You still can use array as "classic" arrays in php, just the way you think.
For example :
<?php
$array = array("First", "Second", "Third");
echo $array[1];
?>
You can then add different values <?php $array[] = "Forth"; ?> and it will be indexed in the order you specified it.
Notice that you can still use it as an associative array :
<?php
$array["newValue"] = "Fifth";
$array[1] = "ReplaceTheSecond";
$array[10] = "";
?>
Arrays in PHP can either be based on a key, like 0 or "key" => "value", or values can just be "appended" to the array by using $array[] = 'value'; .
So:
$mine = array();
$mine[] = 'test';
$mine[] = 'test2';
echo $mine[0];
Would produce 'test';
Haven't tested the code.

Categories