php access array data misunderstanding - php

Given the following array $testarray:
array(1) {
[0]=>
array(3) {
["brand"]=>
string(4) "fiat"
["year"]=>
string(4) "2001"
["color"]=>
string(4) "blue"
}
}
I'm trying to access the data inside with:
foreach($testarray[0] as $key => $value)
{
$newresultado = $value['brand'].$value['year'].$value['color'];
}
echo $newresultado;
I do not get an error returned, but I do get an empty string.
I checked a lot of topics and this should be correct. Why am I getting the empty string?

You are looping through the values under the 0 index so the indexes you are referencing don't exist. Also, if you have more than one then each will overwrite the other so you would use .= instead:
$newresultado = '';
foreach($testarray as $key => $value)
{
$newresultado .= $value['brand'].$value['year'].$value['color'];
}
echo $newresultado;
If there will only ever be one item then there is no need to loop:
echo $testarray[0]['brand'].$testarray[0]['year'].$testarray[0]['color'];
You need to develop with these settings which would have shown you notices and errors:
error_reporting(E_ALL);
ini_set('display_errors', '1');

Try removing [0] from $testarray.

Related

How can I output a value from an array? [duplicate]

This question already has answers here:
How to check if a specific value exists at a specific key in any subarray of a multidimensional array?
(17 answers)
Closed 4 years ago.
array(7) {
[0]=>
array(2) {
["name"]=>
string(14) "form[username]"
["value"]=>
string(1) "1"
}
[1]=>
array(2) {
["name"]=>
string(15) "form[is_active]"
["value"]=>
string(1) "1"
}
[2]=>
array(2) {
["name"]=>
string(8) "form[id]"
["value"]=>
string(1) "9"
}
}
I want to get the id from an array. The output I like to achive is 9.
My approach:
echo $array['form[id]'];
But I don't get an output.
When you use $array['form[id]']; you are looking for the key called 'form[id]' which will not work because the keys of your array are 0, 1 and 2. You can get your desired value by using $array[2]['value']. However this will always call the 2nd element of your array, which might not be what you want. A more dynamic solution would be something like this:
foreach ($array as $element) {
if ($element['name'] == 'form[id]') {
echo $element['value'];
break;
}
}
This will loop through your whole array and check the names of each element. Then when it matches your desired name it will print the value for that exact element.
The easiest way might be to just first re-index the array using array_column. Then you can use the name field as the key:
$array = array_column($array, null, 'name');
echo $arr['form[id]']['value'];
// 9
See https://3v4l.org/L1gLR
You could use a foreach and check for the content .. but the content for index 'name' is just a string form[id]
anyway
foreach( $myArray AS $key => $value){
if ($value['name'] == 'form[id]' ) {
echo $key;
echo $value;
}
}
You are trying to get the value as if it's an associative array (sometimes called a dictionary or map), however it's a plain or indexed array.
Get the value you want by calling $array[2]["value"]
You can also use some of the higher level functions such as array_search; then you could use:
$id = array_search(function($values) {
return $values['name'] == 'form[id]';
}, $array)["value"];
So I think you need to filter the array to find the element you need first, then output that element's value:
$filtered_array = array_filter($your_array, function(element){
return element['name'] == 'form[username]';
});
if (!empty($filtered_array)) {
echo array_pop($filtered_array)['value'];
}

foreach results in endless loop

I have an array stored in $_SESSION:
var_dump($_SESSION['session_article']);
//result:
array(2) {
[0]=> array(2) {
["id"]=> string(1) "3"
["amount"]=> int(2)
}
[1]=> array(2) {
["id"]=> string(2) "13"
["amount"]=> int(1)
}
}
If I do:
for($artKey = 0;$artKey < count($_SESSION['session_article']);$artKey++){
$cartArt = $_SESSION['session_article'][$artKey];
//stuff that doesn't affect key or value
}
everything is fine ...but if I do:
foreach($_SESSION['session_article'] as $artKey => $cartArt){
//stuff that doesn't affect key or value
}
the page won't stop to load (infinite loading, like the foreach never terminates)
I would like to you know that the computer is not a dumb machine, so whenever you do not get the right result then its not the computers problem, it is in how you code.
So lets take a look at your code first you var_dump($_SESSION['session_article']) you got an array with two elements each being an associative array. Now observe that this is an array of arrays so you code in scenario 2 is wrong.
If it were to be just a single array say $myArray = ['Simon', 'Peter', 'You'] then this woul have worked fine (note I used the short array syntax here you can use array() if you prefer). But the problem is you have multidimensional Arrays so you could should be
foreach($_SESSION['session_article'], list($a,))
{
//stuffs here
}
or better walk through the $_SESSION['session_article'] as an associative array like so
$myArray = $_SESSION['session_article']
$field = count($myArray, COUNT_RECURSIVE - (int)2)
for ($record = 0; $record < $myArray.length; $record++) {
//record number
for ($field = 0; $field < $field ; $field++) {
//combine record and field here
}
}
Hope I could lend a helping hand?
Please checkout
http://php.net/manual/en/function.count.php
http://php.net/manual/en/control-structures.foreach.php
They really have a good doc, just take you time.

advanced unset the value form array PHP

I have two arrays, what consist arrays. I need to merge these arrays recursive. But I need to do this action few times, and
array_merge_recursive()
will apend my data twice, I want to remove element what already exist in target array.
$messages array :
array(2) {
["messages"]=>
array(2) {
["test.testik"]=>
string(13) "Це тест"
["test2313.tes31231tik"]=>
string(23) "це тестончик"
}
["validators"]=>
array(4) {
["valid.validik"]=>
string(36) "Це валідне значення"
["joga.jimbo"]=>
string(27) "Джімбо торбінс"
["validka.invalidka"]=>
string(23) "це інвалідка"
["smith.john"]=>
string(17) "джон сміт"
}
}
$allCar array:
array(2) {
["messages"]=>
array(1) {
["test2313.tes31231tik"]=>
string(23) "це тестончик"
}
["validators"]=>
array(2) {
["validka.invalidka"]=>
string(23) "це інвалідка"
["smith.john"]=>
string(17) "джон сміт"
}
}
I wrote some code:
foreach ($messages as $domain => $messagesArray) {
foreach ($allCat as $d => $mess) {
if ($domain == $d) {
foreach ($messagesArray as $ymlkey => $trans) {
foreach ($mess as $ymlk => $transl) {
if ($ymlkey == $ymlk) {
unset($mess[$ymlk]);
}
}
}
}
}
}
Then when I run recursive merge it append the same values to array. What I am doing wrong ?
This:
foreach ($allCat as $d => $mess) {
$mess is a temporary COPY of whatever value your foreach() loop is currently working on. When you do your unset($mess...) later on, you're simply unsetting that temporary copy.
While some might suggest making $mess a reference, this can/will cause problems later on, because $mess will STILL be a reference after the loops end, and reusing the variable later on will now be mucking around with whatever $mess last pointed at in the loop.
Instead, use the full array/object path reference in the unset call:
unset($messages[$domain][$d][$ymlkey][$ymkl])
or whatever it should be. This way you guarantee you're working with the actual "real" array, and not any of the many temporary copies your nested loops are creating.

php array loop to get array

I have a $date array like this:
[1]=> array(11) {
["meetingname"]=> string(33) "win2008connectcurrent0423131"
[0]=> array(3) {
["scoid"]=> string(7) "3557012"
["datecreated"]=> string(19) "2013-05-23 10:02:39"
["numparticipants"]=> string(1) "3"
}
[1]=> array(3) {
["scoid"]=> string(7) "3557012"
["datecreated"]=> string(19) "2013-05-23 14:40:06"
["numparticipants"]=> string(1) "3"
}
}
foreach($date[0] as $key => $meetings){
print "$key = $meetings\n";////yields scoid = 3557012
}
And, as you can see above, I am looping over individual elements. The first element (not indexed) is always meetingname; the rest of the elements are indexed and themselves contain arrays with three elements in each array--in the above code they are [0] and [1].
What I need to do is make the $meetings as an array containing [0] and then [1] etc, depending on the number of elements. So essentially, the output for print should be an array (I can also use var_dump) with key/values of [0] but right not it only outputs individual keys and their values, for example, as you can see above, scoid=3557012. I will need, something all keys/values in the $meetings variable, something like:
{
["scoid"]=> string(7) "3557012"
["datecreated"]=> string(19) "2013-05-23 10:02:39"
["numparticipants"]=> string(1) "3"
}
How can I fix the foreach loop for that?
please Try this. hope it help.
foreach($date as $key => $meetings){
if($key == "meetingname")
continue;
else
print "$meetings\n";
}
You can just create a new array and add the meetings to that one
<?php
$meetings = array();
foreach($date[1] as $key=>$meeting) {
if (!is_int($key))
continue; //only handle numeric keys, incase you ever change the name of the first key 'meetingname'
$meetings[] = $meeting
}
var_dump($meetings);
?>

&Array() - Final Row prefixed with ampersand after Updating Array

I am trying to update only some values of an Array directly. Which is working perfectly. I am using the following method:
foreach( $items as &$item ) {
if( $criteria == 'correct' ) {
// update array
$item['update_me'] = 'updated';
}
}
So I now have an updated array called $items.
However, the problem I have, is when this Array is output to screen (via another foreach loop), the last row of the Array is missing.
If I print the entire array via the var_dump( $items ); method, I noticed that each row is prefixed with Array(9). Yet the last row is prefixed with &Array(9) - notice the leading ampersand. I'm sure this is significant! But I'm unsure what it means. Why is it only applied to the final row in the Array? And how do I get rid of it?
From comment:
array(6) {
[0]=> array(9) {
["item_id"]=> string(4) "1"
["item_description"]=> string(9) "blah blah"
["quantity"]=> string(1) "4"
["unit_cost"]=> string(4) "5.00"
["subtotal"]=> string(4) "20.00"
}
[1]=> &array(9) {
["item_id"]=> string(4) "2"
["item_description"]=> string(9) "blah blah"
["quantity"]=> string(1) "1"
["unit_cost"]=> string(4) "5.99"
["subtotal"]=> string(4) "5.99"
}
}
You must unset $item after loop. Correct code:
foreach( $items as &$item ) {
if( $criteria == 'correct' ) {
// update array
$item['update_me'] = 'updated';
}
}
unset($item);
& sign in the var_dump result specify that this is reference. You can check it by using xdebug_zval_dump() function:
xdebug_zval_dump($item)
You'll see that is_ref=true. In PHP this means that there are another variables pointing to the same zval container (what is zval? see here http://php.net/manual/en/internals2.variables.intro.php).
If you're using & in loop you must always unset reference after the loop to avoid hard-to-detect errors.
I'm not sure if it is the case here, but by-reference foreach loops are known to cause these kind of problems if the reference is not unset after the loop (there's a warning about it in the manual). Try adding unset($item); right after the update foreach finishes and see if it solves the problem.
i think that's not the nicest way to do this. i'd suggest doing it this way:
foreach( array_keys($items) as $itemkey ) {
if( $criteria == 'correct' ) {
// update array
$items[$itemkey]['update_me'] = 'updated';
}
}

Categories