Php how to include in a variable name another variable - php

In the example are two arrays, but actually may be other number of arrays (i do not know how many arrays i may have).
$some_name = array ( "Volvo_0",220,180, );
$array_name_for_variable[]='some_name';//here i create another array latter to loop through
$another_name = array ( "Volvo_1",221,181, );
$array_name_for_variable[]='another_name';
In the example i just want to print_r the arrays i may have. So i loop through $array_name_for_variable. Like
foreach( $array_name_for_variable as $i_array_name_for_variable => $val_array_name_for_variable ) {
trying to print particular array (like print_r($some_name)), using this
echo '<pre>', print_r($['val_array_name_for_variable'], true), '</pre> $val_array_name_for_variable __<br/>';
but see error Parse error: syntax error, unexpected '[', expecting T_VARIABLE or '$'
}
This print_r($['val_array_name_for_variable']) is wrong. Tried this print_r( $[$val_array_name_for_variable] );. Also got error.
Any ideas what need to change.
Why all this and what i need...
I have 12 arrays, but i do not know which of 12 would be used in one particular page.
So page loads, some of the 12 arrays are defined (used).
I may write like if array_1 exists, then long html code using variables from the array_1.
Then again if array_2 exists and not empty, then repeat the same html code with variables from array_2.
But instead of copy-paste (repeating) html code i decided to loop through arrays existing in opened page and the long html code write only once.

You could solve the problem with:
$some_name = array ( "Volvo_0",220,180, );
$array_name_for_variable[]=$some_name;
$another_name = array ( "Volvo_1",221,181, );
$array_name_for_variable[]=$another_name;
then iterate through it:
foreach( $array_name_for_variable as $i_array_name_for_variable => $val_array_name_for_variable ) {
echo '<pre>', print_r($val_array_name_for_variable, true), '</pre><br/>';
}
This will print all the elements in $array_name_for_variable.
Comment if you need any more changes to the output.
Explanation: What the code is actually doing is iterating through all elements of the array $array_name_for_variable. They it creates a key => value for each element in it. The value ($val_array_name_for_variable) on the first iteration would be: $some_name. The key ($i_array_name_for_variable) - the element position in the array, so on the first iteration it would be 0 (as it always start from 0).
If you don't need the element position you could do it like this:
foreach( $array_name_for_variable as $val_array_name_for_variable ) {
echo '<pre>', print_r($val_array_name_for_variable, true), '</pre><br/>';
}
It would generate exactly the same output as the previous code snippet.
For adding elements to the array you have to pass a variable and you were passing just a string.
EDIT:
Based on the newly added info the code should be:
foreach( $array_name_for_variable as $i_array_name_for_variable => $val_array_name_for_variable ) {
if (array_key_exists($i_array_name_for_variable, $val_array_name_for_variable)) {
echo '<pre>', print_r($val_array_name_for_variable, true), '</pre><br/>';
} else {
//Code if the array does not exist.
}
}
References:
http://php.net/manual/en/control-structures.foreach.php
http://php.net/manual/en/function.array-push.php
http://php.net/manual/en/function.array-key-exists.php

You may want to do something like this
$some_name = array ( "Volvo_0",220,180, );
$array_name_for_variable['some_name']= $some_name ;
$another_name = array ( "Volvo_1",221,181, );
$array_name_for_variable['another_name']= $another_name ;
foreach( $array_name_for_variable as $i_array_name_for_variable => $val_array_name_for_variable ) {
print_r($val_array_name_for_variable);//prints the array
print_r($i_array_name_for_variable);// print the keys ex :- some_name
}

Related

increment value inside an array of arrays (if key is non-existent, set it to 1)

Question has been updated to clarify
For simple arrays, I find it convenient to use $arr[$key]++ to either populate a new element or increment an existing element. For example, counting the number of fruits, $arr['apple']++ will create the array element $arr('apple'=>1) the first time "apple" is encountered. Subsequent iterations will merely increment the value for "apple". There is no need to add code to check to see if the key "apple" already exists.
I am populating an array of arrays, and want to achieve a similar "one-liner" as in the example above in an element of the nested array.
$stats is the array. Each element in $stats is another array with 2 keys ("name" and "count")
I want to be able to push an array into $stats - if the key already exists, merely increment the "count" value. If it doesn't exist, create a new element array and set the count to 1. And doing this in one line, just like the example above for a simple array.
In code, this would look something like (but does not work):
$stats[$key] = array('name'=>$name,'count'=>++);
or
$stats[$key] = array('name'=>$name,++);
Looking for ideas on how to achieve this without the need to check if the element already exists.
Background:
I am cycling through an array of objects, looking at the "data" element in each one. Here is a snip from the array:
[1] => stdClass Object
(
[to] => stdClass Object
(
[data] => Array
(
[0] => stdClass Object
(
[name] => foobar
[id] => 1234
)
)
)
I would like to count the occurrences of "id" and correlate it to "name". ("id" and "name" are unique combinations - ex. name="foobar" will always have an id=1234)
i.e.
id name count
1234 foobar 55
6789 raboof 99
I'm using an array of arrays at the moment, $stats, to capture the information (I am def. open to other implementations. I looked into array_unique but my original data is deep inside arrays & objects).
The first time I encounter "id" (ex. 1234), I'll create a new array in $stats, and set the count to 1. For subsequent hits (ex: id=1234), I just want to increment count.
For one dimensional arrays, $arr[$obj->id]++ works fine, but I can't figure out how to push/increment for array of arrays. How can I push/increment in one line for multi-dimensional arrays?
Thanks in advance.
$stats = array();
foreach ($dataArray as $element) {
$obj = $element->to->data[0];
// this next line does not meet my needs, it's just to demonstrate the structure of the array
$stats[$obj->id] = array('name'=>$obj->name,'count'=>1);
// this next line obviously does not work, it's what I need to get working
$stats[$obj->id] = array('name'=>$obj->name,'count'=>++);
}
Try checking to see if your array has that value populated, if it's populated then build on that value, otherwise set a default value.
$stats = array();
foreach ($dataArray as $element) {
$obj = $element->to->data[0];
if (!isset($stats[$obj->id])) { // conditionally create array
$stats[$obj->id] = array('name'=>$obj->name,'count'=> 0);
}
$stats[$obj->id]['count']++; // increment count
}
$obj = $element->to->data is again an array. If I understand your question correctly, you would want to loop through $element->to->data as well. So your code now becomes:
$stats = array();
foreach ($dataArray as $element) {
$toArray = $element->to->data[0];
foreach($toArray as $toElement) {
// check if the key was already created or not
if(isset($stats[$toElement->id])) {
$stats[$toElement->id]['count']++;
}
else {
$stats[$toElement->id] = array('name'=>$toArray->name,'count'=>1);
}
}
}
Update:
Considering performance benchmarks, isset() is lot more faster than array_key_exists (but it returns false even if the value is null! In that case consider using isset() || array_key exists() together.
Reference: http://php.net/manual/en/function.array-key-exists.php#107786

Array ( [0] => Array ... problems extracting array values

I am trying to run a function that gets information from a DB and returns an array of the values, so I can then extract it on the page.
Inside the function, after my query I have the following code:
$example_array = array();
while ($row = mysql_fetch_assoc($query) {
$example_array[] = $row;
}
return $example_array;
And there ends my function. Outside of it, I have this:
extract($example_array);
And I would assume I could then directly echo any of the variables that were previously in $example_array, e.g. <?= $example_var ?> but they do not contain any data.
Running print_r($example_array); gives an array that looks like this:
Array ( [0] => Array ( [example_var] => Example String ) )
The start of that code makes me think my array is somehow "lost" inside another array's first ([0]) value, and as such is not extracting correctly.
Have I gone about adding data to that initial $example_array incorrectly?
When you do $example_array[] = $row;, you assign the current row to a new index of $example_array. If you want to access it like $example_array['row_name'], you'd have to assign it like this:
$example_array = $row;
But when you do this, $example_array will be overwritten until it has reached the last row (which means that $example_array will always contain the last row from the query). If you just want the first row, you can do this and skip the whole while loop:
$example_array = mysql_fetch_assoc($query);
Maybe :
$example_array = array();
while ($row = mysql_fetch_assoc($query) {
array_push($example_array, $row['exemple_var']);
}
return $example_array;
The issue is that mysql_fetch_array would have meant $row['row_name'] was valid.
As you added $row to the array $example_array, you now need to access it via it's array id too, such as;
$example_array[0]['row_name'], $example_array[1]['row_name'] etc.
What exactly are you trying to achieve? May be easier to offer assistance if we know.

PHP- Get each value of an associative array in a foreach loop, then apply a function and echo the result

I have a piece of code similar to below:
$list_links = array(
[0] => Array // Here I get this error message Parse error: syntax error, unexpected '[', expecting ')'
(
"http://test.com/1/",
"http://test.com/2/"
),
[1] => Array
(
"http://test.com/3/",
"http://test.com/4/"
)
);
//Code stops to execute here
foreach($list_links as $link) {
DoWork($link, $db_connect);
if ($list_links[0]) {
echo "this URL is from the 0 list";
} else if ($list_links[1]) {
echo "this URL is from the 1 list";
}
}
//DoWork function works well and is already tested
function DoWork($link, $db_connect){
...
...
...
}
The problem is that the code stops to execute the DoWork() function when it reaches the foreach() loop because it can not get each URL from the list.
Below are my questions:
1. Could you please see if foreach($list_links as $link) syntax is correct?
2. Are the if formats of if ($list_links[0]) and if ($list_links[1]) correct to echo the messages?
In this context, foreach($list_links as $link), $link is not the URL, it is an array of URLs. Try a nested foreach instead:
foreach ($list_link as $link_array) {
foreach ($link_array as $link) {
DoWork($link, $db_connect);
}
}
This will solve the first part of your problem. However, I'm not sure what you're trying to accomplish with if($list_links[0]) ... . This just checks if $list_links[0] is true or false, essentially.
Further, regardless of what you're trying to do, it doesn't seem like much of an error check, because, given your data, each URL will always be apart of either $list_link[0] or $list_link[1]. If you want to simply state from which list each URL comes from, try this:
foreach ($list_link as $key=>$link_array) {
foreach ($link_array as $link) {
DoWork($link, $db_connect);
echo 'this url is from the '.$key.' list';
}
}
In regard to Parse error: syntax error, unexpected '[', expecting ')':
Remove the brackets from the keys. When declaring an array, they are not used.
$list_links = array(
0 => array
(
"http://test.com/1/",
"http://test.com/2/"
),
1 => array
(
"http://test.com/3/",
"http://test.com/4/"
)
);
Note that if the key to an array element is a string, you must wrap it in quotes:
$array = array ('key' => 'value')
Further note that the default keys for an array are integers starting from 0, so in your case, you could simply remove the keys altogether to get the same result:
$list_links = array(
array("http://test.com/1/", "http://test.com/2/"),
array("http://test.com/3/", "http://test.com/4/")
);
This will automatically assign these two elements the keys 0 and 1, without the need to explicitly declare such. See a demo.
I wouldn't suggest doing a DB call within a loop like this, but to answer your question:
Assign a variable to the function result
$list_links = DoWork($link, $db_connect);
if ($list_links[0]) {
echo "this URL is from the 0 list";
} else if ($list_links[2]) {
echo "this URL is from the 1 list";
}
Syntax error
$list_links = array(
[0] => Array
(
"http://test.com/1/",
"http://test.com/2/", <---- remove this ,
),
[1] => Array
(
"http://test.com/3/",
"http://test.com/4/", <---- remove this ,
)
);
It could be this:
foreach($list_links as $link) {
DoWork($link, $db_connect);
if (in_array($links, $link_list[0])) {
echo "this URL is from the 0 list";
} elseif (in_array($links, $link_list[1])) {
echo "this URL is from the 1 list";
}
}
Notice that I use the recursive features of in_array() to check to see if the $links array has values in the 'zero' array $link_list[0], or the 'one' array $link_list[1].
PHP Manual: in_array()

Condition failing even if the array values are empty

I have a piece of code where the condition fails even when the array is empty.
This is the code:
echo "<pre>";
print_r($_FILES['jform']['name']['gallery']);
which outputs
Array
(
[0] =>
)
This is the condition:
$galfile = $_FILES['jform']['name']['gallery'];
if(!empty($galfile))
{
//do something
}
It should fail, but the program enters the if block. Why?
As you can see from the print_r() the array is NOT empty - it has one element, which on the other side looks like white space or empty.
Update
I would recommend reading POST method uploads, where you'll learn that name is the original name of the file and tmp_name is a random name of the temporary file, that has been just uploaded.
According to my experience you should check the Error Messages.
The check you're interested is:
foreach ( array_keys( $_FILES['jform']['gallery'] ) AS $key ) {
if ( UPLOAD_ERR_OK == $_FILES['jform']['gallery']['error'][$key] ) {
// do the stuff with the uploaded file in $_FILES['jform']['gallery']['tmp_name'][$key]
}
}
Keep an eye on the names of the arrays where gallery is before name.
As you can see your array is not empty it has a blank element.
The work around is array_filter which will eliminate blank data
$array = array(0=>'');
$array1 = array_filter($array);
print_r($array1);
if(!empty($array1)){
echo "has elememt";
}else{
echo "empty";
}
This is what u need
UPDATE
What if the value contains multiple spaces, yes this could be handled using a call back function
$array1 = array_filter($array,"call_back_function");
function call_back_function($val){
return trim($val);
}
In your case print_r() told you that galfile == array('') // 1 element is in the array
According to the documentaion only array() // 0 elements is considered empty. So the if statement is executed correctly.
In your case you should write:
$galfile = $_FILES['jform']['name']['gallery'];
if(!empty($galfile) && !empty($galfile[0]) )
{
//do something
}
When you working with arrays, before checking for empty you can sanitize your array using array_filter or the similar functions:
$galfile = array_filter($_FILES['jform']['name']['gallery']);
if(!empty($galfile))
{
//do something
}
But when you use global array _FILES, more correctly is checks for error:
if($_FILES['jform']['error']['gallery'] == 0)
{
//do something
}
P.S. If you want to filtering all array elements, you can use filter_var_array

How to search array for duplicates using a single array?

I am checking a list of 10 spots, each spot w/ 3 top users to see if a user is in an array before echoing and storing.
foreach($top_10['top_10'] as $top10) //loop each spot
{
$getuser = ltrim($top10['url'], " users/" ); //strip url
if ($usercount < 3) {
if ((array_search($getuser, $array) !== true)) {
echo $getuser;
$array[$c++] = $getuser;
}
else {
echo "duplicate <br /><br />";
}
}
}
The problem I am having is that for every loop, it creates a multi-dimensional array for some reason which only allows array_search to search the current array and not all combined. I am wanting to store everything in the same $array. This is what I see after a print_r($array)
Array ( [0] => 120728 [1] => 205247 ) Array ( [0] => 232123 [1] => 091928 )
There seems to be more to this code. As there are variables being called in it that aren't defined, such as $c, $usercount, etc.. And using array_search with the 2nd parameter of $array if it doesn't exist is not a good idea also. Since it seems like $array is being set within the if statement for this only.
And you don't seem to be using the $top10 value within the foreach loop at all..., why is this?
It would help to see more of the code for me to be able to help you.

Categories