php iterate over an array made up of strings, instead of objects - php

I need to iterating over an array made up of strings, not objects. I've tried hunting and implementing other stackoverflow answers but dont seem to be able to make this work.
The array:
var_dump(`$myids`);
array(3) {
[0]=>
string(2) "45"
[1]=>
string(2) "46"
[2]=>
string(2) "47"
}
I tried:
$myids=$_POST['myids'];
foreach ($myids as $value){
$value['myids'];
}
Gives the error - Illegal string offset 'myids'.
Then I tried:
$myids=$_POST['myids'];
foreach ($myids as $value){
$value->myids;
}
Gives the error - Trying to access proprieties of a non object.
So I thought maybe adding the key to the foreach but that wasnt the solution. At the risk of sounding dumb, what is the solution to access each value of the array?

Well, there is no "myids" key in the array. You are using purely numeric IDs, so none of the keys will be named in your array.
$myids=$_POST['myids'];
foreach ($myids as $value){
echo $value;
}
This is unrolling each row of $myids into $value. Once it unrolls and enters the loop, you should not try to access $myids, but should work solely with $value, which represents ONLY the current row.
On the first iteration, $value will contain:
string(2) "45"
On the second iteration, $value will contain:
string(2) "46"
Third iteration:
string(2) "47"
As you can see, $value only ever contains string values, so there are no arrays or keys to access within. It's pulling one row on each iteration of the loop and inserting it directly into $value. As such, you only need to echo $value directly.

Related

How to return id of each array in Session Array?

I am trying to return the ids of each array in my session cart however at the moment it is not working correctly because i am only returning the position of the array which is not working when i go to remove the item from the array.
So how can i return the actual id of the array code below:
Current Array:
$_SESSION['cart'] = array(1) {
[1]=>
array(3) {
["start"]=>
string(18) "name"
["end"]=>
string(19) "name"
["amount"]=>
string(2) "11"
}
}
From the above i am trying to retrieve 1 from [1]=> where later i will use to delete the array using $_SESSION['cart'][$arrayId];
for now i am counting the loops in the array using $i but this is insufficient.
So to reiterate i am trying to return the "[1]" id from [1]=>, unless there is another method that is better i would be all ears :)
Hope this makes sense everyone.
Alex
Addtional info:
Lets say i am inside the loop at the moment, can i somehow call the id from inside the foreach loop?
To iterate over an array's keys and values, use foreach:
foreach ($_SESSION['cart'] as $key => $value) {
if ($value/* something */) {
echo $key;
}
}
array_keys() is what you need.
If you just need the id of a row in the array, you can do the following:
foreach ($_SESSION['cart'] as $id => $array) {
echo $id; // $id will be the value of the keys of the looped array.
}
$ids = array_keys($_SESSION['cart']);

How to list the keys of an array when the keys are also arrays?

I have a complex array, with structure like the following..
array(3) {
["status"]=>
int(1)
["data"]=>
array(113) {
[0]=>
array(3) {
["id"]=>
string(6) "838424"
["language"]=>
NULL
["work_start_date"]=>
string(19) "2003-04-28 00:00:00"
}
[1]=>
array(3) {
["id"]=>
string(6) "839062"
["language"]=>
NULL
["work_start_date"]=>
string(19) "2014-01-15 12:53:00"
}
}
}
I can get the "id" of a certain element by using something like the following..
print $my_array["data"]["0"]["id"] . "\n";
But what I want to do is loop through the 0,1 etc elements, and I don't know how to do that. I thought something like the following would do it, but it doesn't work.
foreach ($my_array["data"] as $key) {
print $my_array["data"][$key]["id"] . "\n";
}
Any insight would be appreciated
You are a little off on your foreach syntax.
You should either do:
foreach($my_array['data'] as $item) {
print $item['id'] . "\n";
}
Or
foreach($my_array['data'] as $key => $item) {
print "The item at index position '" . $key . "' has an id of '" . $item['id'] . "'\n";
}
In the first case where foreach syntax with single variable name is used, you actually have no information on the key itself, you only get the values at each index location. This sort of syntax is usually only useful for numerically indexed arrays (which you have in this case).
In the second syntax, you get a variable for both the key and the value that you can reference. This is usually most useful for iterating associative arrays, or for iterating numerical arrays where you need to reference the index position.
In either case, the value present in $item would hold only the value for that array element, you would not need reference back to the containing $my_array variable to access this data.
Try something like:
foreach (array_keys($my_array["data"]) as $key) {
print ...
}

decoding an array from json into PHP and unable to access elements of array using keys

I have some JSON similar to the following:
{"internalArray": {"201": "A", "202": "B", "5": "C", "46": "D"},
"data": "ABCDEFG",
"data2": "TSXPIIF"}
I use the following PHP code to decode it:
$jsonOutput = json_decode($output);
I would like to get access to the "internalArray" from the JSON data, so I reference it using the following:
$internalArray = $jsonOutput->{'internalArray'};
When I do a var_dump on $internalArray
object(stdClass)#4 (4)
{ ["201"]=> string(1) "A"
["202"]=> string(1) "B"
["5"]=> string(1) "C"
["46"]=> string(1) "D"
}
I figured out that I could cast this to an array, so I did the following:
$internalArray = (array) $jsonOutput->{'internalArray'};
However, now that I have this array, I can't appear to access it using values like
$internalArray["202"], $internalArray["201"], etc.
When I try to access it via the keys, it returns NULL. However, when I have code like this:
foreach ($internalArray as $key => $value)
{
echo $key . "," . $value;
}
it prints out the values as expected, like "202,A", etc.
However, in the same code if I change it to
foreach ($internalArray as $key => $value)
{
echo $key . "," . $internalArray[$key];
}
it doesn't work!
Can anyone explain why I can't access the values in $internalArray using the keys? Am I doing something fundamentally wrong here?
If you want an associative array, you can ask PHP for an associative array (see documentation for json_decode):
$jsonOutput = json_decode($output, true);
var_dump($jsonOutput['internalArray']);
Produces:
array(4) {
[201]=>
string(1) "A"
[202]=>
string(1) "B"
[5]=>
string(1) "C"
[46]=>
string(1) "D"
}
Back to your issue, your code would still work if the keys in the internal array were not numeric. What is happening here is a little peculiar: PHP doesn't allow you to have numeric strings (eg: '201', '46') as keys for an array.
Numeric strings keys will be converted to numbers keys instead. So when you do $arr['201'] PHP will look for $arr[201] instead. However, when you cast your object into an array, it looks like the array keys remain strings (eg: $arr['201']). Now the actual array has a numeric string key, but whenever you try to access it, PHP looks for an int key and never finds it, giving you NULL.
In fact, the documentation notes that:
If an object is converted to an array, the result is an array whose elements are the object's properties. The keys are the member variable names, with a few notable exceptions: integer properties are unaccessible; (...)
Because the data is not array it is an object. Hence you can't use it by this code snippet
foreach ($internalArray as $key => $value)
{
echo $key . "," . $internalArray[$key];
}
and use for associate array json_decode($output, true);

PHP shuffle not working like expected on my nested array

I have a nested array of arrays, and I want to shuffle the inner arrays. My code looks like this (simplified):
$a = array(array('banana', 'peach'), array('ding', 'dong'), array('oh snow'));
foreach ($a as &$arr) {
shuffle($arr);
}
var_dump($a);
The var_dump outputs this:
array(3) { [0]=> array(2) { [0]=> string(5) "peach" [1]=> string(6) "banana" } [1]=> array(2) { [0]=> string(4) "ding" [1]=> string(4) "dong" } [2]=> &array(1) { [0]=> string(7) "oh snow" } }
As you can see in the output, the first two subarrays work, but the third subarray is linked by reference in the output...
In my full app, this last array-link causes problems, but rather than working around the issue, I want to fix this shuffle thing...
Cheers!
This has to do with how PHP stores references to array elements. It cannot reference an element of an array, only values. Therefore it has to store the value array('oh snow') in a "slot" of the symbol table, then make $arr and $a[2] a reference to that value.
To fix this, unset($arr) after the loop. That way only a single variable is referencing the value, which will then be made a regular array index again. Unsetting references after a foreach is good practice anyway, since there are many such gotchas.

Get value from a array

update
how can I retrieve this value? I need to do that if I will write the value to my database.
array(3) {
[1]=> NULL
[2]=> array(2) {
[123]=>
int(123)
[122]=>
int(0)
}
[3]=> NULL
}
There is something missing in your output. I assume it looks something like:
// var_dump($array);
array(1) {
[0]=>
string(2) "39"
}
so you can access the value with $array[0]. Simple array access.
As arrays are the most important data structure in PHP, you should learn how to deal with them.
Read PHP: Arrays.
Update:
Regarding your update, which value do you want? You have a multidimensional array. This is what you will get:
$array[1] // gives null
$array[2] // gives an array
$array[2][123] // gives the integer 123
$array[2][122] // gives the integer 0
$array[3] // gives null
Maybe you also want (have) to loop over the inner array to get all values:
foreach($array[2] as $key => $value) {
// do something with $key and $value
}
As I said, read the documentation, it contains everything you need to know. Accessing arrays in PHP is not much different than in other programming languages.
The PHP manual contains a lot of examples, it is a pretty could documentation. Use it!
If your array is referenced as $myArray, you can get the string 39 via $myArray[0], i.e., this zeroth item.

Categories