Array call from key not working correctly - php

I'm trying to call to a specific part of an array with the key # and it's not working. I can output the array and see it...
Array
(
[6] => Array
(
[0] => user#domain.com
[1] => user#domain.com
)
[7] => Array
(
[0] => user#domain.com
[1] => user#domain.com
)
[8] => Array
(
[0] => user#domain.com
[1] => user#domain.com
)
)
This array is $emailDB. I can call to the array manually with $emailDB[7] and it works, but if my call is dynamic like this it won't work...
<?php
$value = 7;
print_r($emailDB[$value]);
?>
I've never had an issue like this with an array so it's very odd. What really sucks is I'm under deadline with a form not working on a client's site...joy.
We tried this with no luck...
<?php
$value = 7;
print_r($emailDB[intval($value)]);
?>
I thought intval() would assist but it did not.

You're post implies a bug in php itself, which I highly doubt. What's more likely is that what you posted doesn't properly represent the code you're running.
Why don't try this. Make a brand new empty php file. Hardcode the array keys and values and assign them to the $emailDB variable, and then try
$value = 7;
print_r($emailDB[$value]);
You will see you don't have the problem that you claim. You have now started the debugging process, and now you can look at the working, and non working code to compare the difference.

Well, you are echoing an Array, which I assume is printing "Array" onto your screen. If you want to echo the actual contents of the array, you need to use print_r($array) or echo print_r($array, true). You can also try putting the value in quotes, like $emailDB["{$value}"] to see if that works, I sometimes have troubles with integers not going into things properly.

I agree with you all. It had to have been something whacky with how we were pulling in the data somehow. It was a tab-separated file we were exploding. I just re-wrote the whole thing entirely and imported the data into MySQL and all was well.
In hindsight, I have a sneaking suspicion it was a trim() command that was needed and likely nothing more. Dang it...too late, but I learned something about checking over the code for those types of things.

Related

Having trouble extracting data from PDO array

It might be the late hour or user error but I'm having trouble extracting variables from a PDO, where it would normally work. When I print_r my results by doing $array->results(), I get the following line:
Array ( [0] => stdClass Object ( [messageid] => 1 [fromid] => 2 [toid] => 1 [message] => Hello! ) )
However, on other projects when working with other people I have then just referred to the variable like this:
$result['message']
This is obviously after the line
$result = $array->results();
I've been troubleshooting and come to no conclusions, but I'm terrible at managing arrays so it could be something super simple. Any ideas? Thanks!
Since the result seems objects within array, so get your array and access object(s) inside it, to get message object from your $result, just do:
echo $result[0]->message;

PHP API returns an array - need to reuse it in variables

I have a PHP script that dumps data from an API.
The dump is an array
print_r($answer);
outputs
Array ( [success] => 1 [serial] => s001 [url] => http://gooole.com )
I want to have another variable called $url that holds the value url from the array (held in $answer) in PHP.
I'm unfamiliar with this.
check out extract() it will take the keys from an array, and create variable of the same name to store them in. There are a few flags you can pass it, to determine exactly what it does with things like pre-existing variables of the same name.
EDIT: as mentioned in the comments on your question, though, $url = $answer['url']; is probably the simplest way to go.

Show array as written with rand inside

I have an array such as:
$var = array('hi','ho',rand(2,5));
What I would like to echo is the entire array, exactly as written.
Normally when you try a print_r, it shows as:
Array (
[0] => hi
[1] => ho
[2] => 3
)
But I want:
Array (
[0] => hi
[1] => ho
[2] => rand(2,5)
)
You can get this with file_get_contents, but is there any way to do so within the actual PHP file?
I don't think it's possible because when array is created, random value is assigned to element with index 2 and you cannot check how this value was created.
I don't think it's possible, since the rand is already evaluated as soon as you set the array to some variable.
A workaround would be the hold the expression as a string and then eval it when you need it. Like this:
$varStr = "array('hi','ho',rand(2,5))";
echo $varStr;
// when you actually need it
$var = eval($varStr);
However, this is almost never a good idea. Providing a use-case where you need this might help come up with a better solution.

Why does the sort order of multidimensional child arrays revert as soon as foreach loop used for sorting ends?

I have a very strange array sorting related problem in PHP that is driving me completely crazy. I have googled for hours, and still NOTHING indicates that other people have this problem, or that this should happen to begin with, so a solution to this mystery would be GREATLY appreciated!
To describe the problem/question in as few words as possible: When sorting an array based on values inside a multiple levels deeply nested array, using a foreach loop, the resulting array sort order reverts as soon as execution leaves the loop, even though it works fine inside the loop. Why is this, and how do I work around it?
Here is sample code for my problem, which should hopefully be a little more clear than the sentence above:
$top_level_array = array('key_1' => array('sub_array' => array('sub_sub_array_1' => array(1),
'sub_sub_array_2' => array(3),
'sub_sub_array_3' => array(2)
)
)
);
function mycmp($arr_1, $arr_2)
{
if ($arr_1[0] == $arr_2[0])
{
return 0;
}
return ($arr_1[0] < $arr_2[0]) ? -1 : 1;
}
foreach($top_level_array as $current_top_level_member)
{
//This loop will only have one iteration, but never mind that...
print("Inside loop before sort operation:\n\n");
print_r($current_top_level_member['sub_array']);
uasort($current_top_level_member['sub_array'], 'mycmp');
print("\nInside loop after sort operation:\n\n");
print_r($current_top_level_member['sub_array']);
}
print("\nOutside of loop (i.e. after all sort operations finished):\n\n");
print_r($top_level_array);
The output of this is as follows:
Inside loop before sort operation:
Array
(
[sub_sub_array_1] => Array
(
[0] => 1
)
[sub_sub_array_2] => Array
(
[0] => 3
)
[sub_sub_array_3] => Array
(
[0] => 2
)
)
Inside loop after sort operation:
Array
(
[sub_sub_array_1] => Array
(
[0] => 1
)
[sub_sub_array_3] => Array
(
[0] => 2
)
[sub_sub_array_2] => Array
(
[0] => 3
)
)
Outside of loop (i.e. after all sort operations finished):
Array
(
[key_1] => Array
(
[sub_array] => Array
(
[sub_sub_array_1] => Array
(
[0] => 1
)
[sub_sub_array_2] => Array
(
[0] => 3
)
[sub_sub_array_3] => Array
(
[0] => 2
)
)
)
)
As you can see, the sort order is "wrong" (i.e. not ordered by the desired value in the innermost array) before the sort operation inside the loop (as expected), then is becomes "correct" after the sort operation inside the loop (as expected).
So far so good.
But THEN, once we're outside the loop again, all of a sudden the order has reverted to its original state, as if the sort loop didn't execute at all?!?
How come this happens, and how will I ever be able to sort this array in the desired way then?
I was under the impression that neither foreach loops nor the uasort() function operated on separate instances of the items in question (but rather on references, i.e. in place), but the result above seems to indicate otherwise? And if so, how will I ever be able to perform the desired sort operation?
(and WHY doesn't anyone else than me on the entire internet seem to have this problem?)
PS.
Never mind the reason behind the design of the strange array to be sorted in this example, it is of course only a simplified PoC of a real problem in much more complex code.
Your problem is a misunderstanding of how PHP provides your "value" in the foreach construct.
foreach($top_level_array as $current_top_level_member)
The variable $current_top_level_member is a copy of the value in the array, not a reference to inside the $top_level_array. Therefore all your work happens on the copy and is discarded after the loop completes. (Actually it is in the $current_top_level_member variable, but $top_level_array never sees the changes.)
You want a reference instead:
foreach($top_level_array as $key => $value)
{
$current_top_level_member =& $top_level_array[$key];
EDIT:
You can also use the foreach by reference notation (hat tip to air4x) to avoid the extra assignment. Note that if you are working with an array of Objects, they are already passed by reference.
foreach($top_level_array as &$current_top_level_member)
To answer you question as to why PHP defaults to a copy instead of a reference, it's simply because of the rules of the language. Scalar values and arrays are assigned by value, unless the & prefix is used, and objects are always assigned by reference (as of PHP 5). And that is likely due to a general consensus that it's generally better to work with copies of everything expect objects. BUT--it is not slow like you might expect. PHP uses a lazy copy called copy on write, where it is really a read-only reference. On the first write, the copy is made.
PHP uses a lazy-copy mechanism (also called copy-on-write) that does
not actually create a copy of a variable until it is modified.
Source: http://www.thedeveloperday.com/php-lazy-copy/
You can add & before $current_top_level_member and use it as reference to the variable in the original array. Then you would be making changes to the original array.
foreach ($top_level_array as &$current_top_level_member) {

CakePHP returning double array from find('list) query

I'm using cakephp and am getting back a "double array" where it is giving me 2 arrays where it should be 1, I have looked into the issue as far as cakephp and can't figure it out and just want to move past this for now so I am wondering if anyone knows how to unset a second array if a variable has 2 arrays.. below is the print_r of the array, its just one variable that has this, which I find odd.. so I want to make it so there is not a 2nd set of duplicate values, if I do an array_push it pushes both values for that index into the resulting new array index so that won't work
one variable is equal to the following:
Array ( [0] => 42 [1] => 62 ) Array ( [0] => 42 [1] => 62 )
EDIT:
This is not an issue of my printing out the array twice accidentally, as I said above, with a foreach array_push of the variable, i end up with this, which is odd:
Array ( [0] => 4242 [1] => 6262 )
EDIT:
This is the cakephp database call that I am using, I know I didn't ask this in regards to cakephp but since some people think this is impossible i am posting this just so you can see what it does if you want
$specificfields_array = $this->Mymodel->find('list', array('fields' =>'Mymodel.id'),
'conditions' => array('emailgroup' => $categorynumber, 'sent' => '0');));
EDIT:
This is what a "foreach" array_push is:
$mynewarray = array();
foreach ($specificfields as $specificfields_current) {
array_push ($mynewarray, $specificfields_current);
}
A variable cannot "have two arrays". It can be one array that has two arrays nested. The scenario you describe is impossible (probably there are two print_r there or there is a < character hiding stuff – check the HTML source).
Can you post the controller, the model and the view file with your print_r calls to the http://bin.cakephp.org/ site and post the links back here so we can see all of your code?

Categories