Variable inside of array not working? - php

I am trying to retreive some information outside of an array I have created inside of a loop.
If I hard code the array location things print out as expected. If I add the variable inside of the loop to print each array, I get nothing.
$num = 0;
foreach ( $repeatable_fields as $field ) {
$num++;
$field_playback_format = $field['playback_format'];
print_r($field_playback_format[$num]);
}
Prints nothing. But if I replace $num with a value, say 1, things echo onto the screen.
But if I do:
$num = 0;
foreach ( $repeatable_fields as $field ) {
$num++;
$field_playback_format = $field['playback_format'];
print_r($field_playback_format[1]);
}
This works as expected and prints out what I need. The reason I need to do this inside of a loop is because I have constructed multiple arrays $field_playback_format[1] and $field_playback_format[2] contain different values, but I need to retrieve them both inside the loop.
Am I not able to use a variable in this spot??

Array starts from 0, your script increment immediately the index and you have an error because the last loop try to get an element of array that doesn't exist because the index is +1 than the real value.
try this:
$num = 0;
foreach ( $repeatable_fields as $field ) {
$field_playback_format = $field['playback_format'];
print_r($field_playback_format[$num]);
$num++;
}
Your second script works because you print an existing element. But if you try to print with a major index retrieve an error and you can't see the print_r

Related

PHP Loop array object once, or wild card key?

I have a php array, and inside the array is a reference to another php object with a numerical value.
How can i access the elements in this array without knowing that numerical id (it could be different for each array)?
In the image below, I need to get the values inside field_collection_item like so....
$content['field_image_columns'][0]['entity']['field_collection_item'][133]['field_image']
For the first array key (0) i have done the following...
$i = 0;
while($i <= 2) {
if(isset($content['field_image_columns'][$i])) {
print '<div class="column-' . $i . '">';
foreach ($content['field_image_columns'][$i]['entity']['field_collection_item'] as $fcid => $values) {
// Print field values
}
print '</div>';
}
$i++;
}
Doing a foreach loop for a single array item seems wrong - is there a method i should be using for this use case?
You can select first item of array for example with:
Use array_shift, but it will modify source array:
$cur = array_shift($content['field_image_columns'][$i]['entity']['field_collection_item']);
print $cur['field_image'];
Get keys of array with array_keys and use first element of result as a key
$ks = array_keys($content['field_image_columns'][$i]['entity']['field_collection_item']);
print $content['field_image_columns'][$i]['entity']['field_collection_item'][$ks[0]]['field_image'];
Use current function:
$cur = current($content['field_image_columns'][$i]['entity']['field_collection_item']);
print $cur['field_image'];
As with most programming, there are quite a few ways you could do it. If a foreach works, then it isn't wrong, but it may not be the best way.
// Get the current key from an array
$key = key($array);
If you don't need the key, then you can just get the value from the array.
// Get the current value from an array
$value = current($array);
Both of these will retrieve the first key/value from the array assuming you haven't advanced the pointer.
current, key, end, reset, next, & prev are all array functions that allow you to manipulate an array without knowing anything about the internals. http://php.net/manual/en/ref.array.php

Get value from multi-dimensional array using variable

I want to get keys and values from a multi-dimensional array dynamically, to better explain what I'm trying to achieve please see the code below.
$i = 0;
foreach ($faq as $f) {
$q = 'faq'.$i;
$a = 'faq'.$i.'_answer';
echo $faq['faq1'][$i];
echo $faq['faq1_answer'][$i];
$i++;
}
The literal text above faq1 and faq1_answer needs to be replaced by the variable $q and $a respectively for me to be able to get the keys and values dynamically, but I cannot figure out how to add the variable.
The keys will always be the same, except for the number, which will change from 1 to 99. So with the code above, I can get the value of faq1 but I also need to grab the value of faq2 etc, hence why the variables above would work as I need.
tl;dr faq1 needs to be able to change to faq2 on the next iteration, hence the reason for me using $i.
Maybe like this?
$i = 0;
foreach ($faq as $f) {
$q = 'faq'.$i;
$a = 'faq'.$i.'_answer';
echo $f[$a];
echo $f[$a];
$i++;
}

array isn't combining with loop in php

i've a array problem couldn't just solve it:
here's the code that is already in a foreach loop. i'm getting the $row->class_id value from this loop. it works fine and get me the total students row within an array and i preserved it in $total_student_of_this_class variable. i used another foreach loop for storing the result of first loop and then second loop and so on. but this loop gives only first loop result.
i need to combine the all array of total iteration of the loop.
$total_student_of_this_class =
$this->db->select('student_id')->where('class_id',
$row->class_id)->get('student')->result_array();
echo count($total_student_of_this_class);
// prints 2 in the first row of the output table and 5 in the second
row for me.
$total_student = array();
foreach ($total_student_of_this_class as $tt)
{
$total_student[] = $tt;
}
echo '<pre>';
print_r($total_student_of_this_class);
echo '</pre>'
echo count($total_student);
// prints only 2 outside the loop (not 7)
pls someone help me.
The problem here is seems to be with $total_student = array();: initializing array inside an other loop it always starts it from zero values array, so you get only results from one iteration inside it and doesn't collect all datas.
You can also look at array_merge php function.

add into multidimension array in PHP

I am trying to create/fill two multidimension arrays within a loop.
$internal_array = array();
$external_array = array();
Within a loop, I am trying fill them randomnly, so for example if, for every iteration, my variable is "internal", I'll fill internal_array otherwise external_array.
This array has three cells as shown below.
I am not sure how would I insert into my array, as an example, this is what I am trying:-
$internal_array = array("mystring1", "mynumber1", "order1");
$external_array = array("mystring4", "mynumber4", "order4");
This seems to not work for somereason.
I am hoping that by the end of loop, I'd have a multidimensional array like:-
internal_array = [0] ("mystring1", "mynumber1", "order1")
[1] ("mystring2", "mynumber2", "order2")
[2] ("mystring3", "mynumber3", "order3")
external_array = [0] ("mystring4", "mynumber4", "order4")
[1] ("mystring5", "mynumber5", "order5")
[2] ("mystring6", "mynumber6", "order6")
Any idea please?
Thanks.
In the loop with every occurrence you are re-populating the same variable over and over again $internal_array = [some_value], so it will contain the last values populated only, using $internal_array[] = [some_value] will add every item in the loop as a subsequent array member
for($i=0; $i<count; $i++){
if ($category == "internal") {
$internal_array[] = array("mystring1", "mynumber1", "order1");
}
elseif ($category == "external") {
$external_array[] = array("mystring4", "mynumber4", "order4");
}
}
You could also add them all in one shot like this:
array_push(
$internal_array,
array("mystring1", "mynumber1", "order1"),
array("mystring2", "mynumber2", "order2"),
array("mystring3", "mynumber3", "order3")
);
See array_push()

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.

Categories