My array looks like this:
Array
( [myarr] => Array (
[504] => 2
[508] => 25
)
)
Is it possible to echo a certain position of this array? I have tried:
echo $_SESSION['myarr'][0][0];
I can't seem to get anything to echo back.
EDIT: to be more specific.. Is it possible to echo it based on numeric index?
Use array_keys() to get the keys into an array. Then access the 2D array using indexes in the keys array. Not that this is the best way to do this but it is a way to use numeric indexes to solve your problem.
$keys = array_keys($_SESSION["myarr"]);
$zero = $_SESSION["myarr"][$keys[0]];
It's just a regular nested array. You use the index keys just as you normally would:
echo $_SESSION['myarr'][504]; //2
echo $_SESSION['myarr'][508]; //25
Have a look at Get the first element of an array.
The following should work (untested, so no guaranties):
echo array_shift(array_values($_SESSION))[0][0];
Yes it is possible
print $array['myarr'][508]; // 25
This is getting ugly.
$i = 1;
foreach ($myarr as $array) {
if ($i == 2) echo $array;
$i++;
}
Related
I am trying to compare two non-associative arrays to create a new array with the matches.
This is what I have though:
//This array has several entries
$a_firstarray = Array();
//This array has less entries than the first array
$a_secondarray = Array();
//This array should contain the matches of the first array and the second array in no particular order
$a_mergedarray
for($i=0;$i <=count($a_firstarray);$i++){
for($a=0;$a <=count ($a_secondarray);$a++){
if($a_firstarray[$i] == $a_secondarray[$a]){
$a_mergedarray[] = $a_activecategory[$i];
}
}
}
It doesn't work for some reason. I am also sure that PHP has some sort of function that does this. Any ideas? thanks in advance.
This is known as the "intersection" of two arrays. PHP provides array_intersect.
use array_intersect.
$result = array_intersect($array1, $array2);
Are you looking for array_intersect()?
http://php.net/manual/en/function.array-intersect.php
How to remove first dimension in multidimension array
array(
[0] => array(
[0]->1
[1]->2
)
)
Now echo
echo id[0][1];
how to get
echo id[0];
Use array_shift
$new_array = array_shift($array);
This is a bit trivial. Putting answer in different format than original answer above to not hide logic of what needs to happen behind a function call (though other answer is totally valid).
$new_array = $old_array[0];
var_dump($new_array);
I have an array, and when i echo it i get the following output;
Array[{"name":"Kat","age":"10"}]
Now, i need to add an additional filed into this; so finally it should appear as;
Array[{"message":"Success","name":"Kat","age":"10"}]
if $arr is my array, how am i going to append "message":"Success" ?
Sorry, i don't have any code to demonstrate my workings, i am stuck here. i would appreciate it if anyone can help me.
Your array content looks like JSON to me. But, if your array are actually just PHP arrays, then do:
$arr = array('name' => 'Kat', 'age' => '10');
$arr['message'] = 'Success';
If it is a JSON encoded array:
$arr = json_decode('{"name":"Kat","age":"10"}' , true)); //true decodes to an array and not a standard object
$arr['message'] = 'Success';
echo $arr;
//If you want it back in JSON
$json = json_encode($arr);
echo $json;
Like Waygood said if you want to add a value to the end of an array just use:
$array[] = $value; or $array['somekey'] = $somevalue;
However, if you need to add a value to the beginning of the array (like your example) you can use:
array_unshift($array, $value);
Alternatively, if you need to add a key and a value to the beginning you can simply make an array with the key => value pair and merge the two arrays like so:
$firstArray = array("message" => "Success");
$newArray = array_merge($firstArray, $secondArray);
For reference, here are the links to the php.net documentation:
array_unshift
array_merge
what about $arr["message"]="Success";?
To add a named field, you can just use this:
$array['message'] = 'Success';
To add a unnamed field, this is the way to do it:
$array[] = $value;
There are multiple ways of doing it.
PHP array functions
http://php.net/manual/en/function.array-push.php
http://php.net/manual/en/function.array-merge.php
The + operator
Or like others mentioned using $arg['var'] =
Just define "message":"Success" as another array and use push, merge or +
Also looks like you have it Json encoded. You will need to handle that as well.
The array functions only work with regular arrays, not encoded strings.
Try this:
$arr = array("name"=>"Kat","age"=>"10");
print_r($arr);
$arr = array_merge(array("message" => "Success"), $arr);
print_r($arr);
$index = 0;
foreach ($sxml->entry as $entry) {
$array + variable index number here = array('title' => $title);
$index++;
}
I'm trying to change an array name depending on my index count. Is it possible to change variable name (ie. $array1, $array2 $array3 etc.) in the loop?
Edit:
After the loop has finished, I will generate a number number (depending on the count of $index) and then use this array... probably it's a stupid way of accomplishing what Im trying to do, but I don't have a better idea.
You might want to try this instead:
$index = 0;
$arrays = array();
foreach ($sxml->entry as $entry) {
$arrays[$index] = array('title' => $title);
$index++;
}
While it is technically possible to do what you are asking, using an array of arrays will probably work better from you.
This type of indexing is exactly what arrays are designed for, you have a lot of items and want to be able to refer to them by number.
Unless you have a very specific reason to use the name of the variable to represent it's number you will probably have a much simpler time using it's index in the outer array.
Yes you can user an associate array. Generating a string dynamically based on the iteration number and using that as a key in the array.
You can use variable variables. php.net
PHP supports Variable variables:
$num = 1;
$array_name = 'array' . $num;
$$array_name = array(1,2,3);
print_r($array1);
http://php.net/manual/en/language.variables.variable.php
I have a multi-dimensional array like
Array
(
[0] => Array
(
[ename] => willy
[due_date] => 12:04:2011
[flag_code] => 0
)
[1] => Array
(
[Father] => Thomas
[due_date] => 13:04:2011
[flag_code] => 0
)
[2] => Array
(
[charges] => $49.00
)
)
i want to display values of array using php. but still fail. please any one help me to do this task....?
Since you're so adamant that this be accomplished using only for loops, I have to assume this is a homework question. Because of this, I'll point you to several PHP manual pages in the hopes that you'll review them and try to learn something for yourself:
Arrays
For Loops
Foreach Loops
Now, I'm going to break your actual question a few different questions:
Is it possible to display a multidimensional array using for loops?
Yes. It's entirely possible to use a for loop to iterate over a multidimensional array. You simply have to nest for loops inside for loops. i.e. you create a for loop to iterate over the outer array, then inside that loop you use another for loop to iterate over the inner array.
How can I iterate over a multidimensional array using a for loop?
Generally, when you use a for loop, the loop will look something like this:
for($i = 0; $i < $maxValue; $i++) {
// do something with $1
}
While this works well for indexed arrays (i.e. arrays with numeric keys), so long as they have sequential keys (i.e. keys which use each integer in order. for example, an array with keys 0, 1, and 2 is sequential; an array with keys 0, 2, and 3 is not because it jumps over 1), this doesn't work well for associative arrays (i.e arrays with text as keys - for example, $array = array("abc" = 123);) because these arrays won't have keys with the numerical indexes your for loop will produce.
Instead, you need to get a bit creative.
One way that you could do this is to use array_keys to get an indexed array of the keys your other array uses. For example, look at this simple, one-dimensional array:
$dinner = array(
"drink" => "water",
"meat" => "chicken",
"vegetable" => "corn"
);
This array has three elements, each with an associative key. We can get an indexed array of its keys using array_keys:
$keys = array_keys($dinner);
This will return the following:
Array
(
[0] => drink
[1] => meat
[2] => vegetable
)
Now, we can iterate over the keys, and use their values to access the associative keys in the original array:
for($i = 0; $i < count($keys); $i++) {
echo $dinner[$keys[$i]] . "";
}
As we iterate over this loop, the index $i will be set to hold each index of the $keys array. The associated element of this key will be the name of a key in the $dinner array. We then use this key name to access the $dinner array elements in order.
Alternatively, you could use a combination of the reset, current and next functions to iterate over the values in the array, for example:
for($element = current($dinner);
current($dinner) !== false;
$element = next($dinner)
) {
echo $element . "<br />";
}
In this loop, you initialize the $element variable to be the first element in the array using reset, which sets the array pointer to the first element, then returns that element. Next, we check the value of current($dinner) to ensure that there is a value to process. current() returns the value of the element the array pointer is currently set at, or false if there is no element there. Finally, at the end of the loop, we use next to set the array pointer ahead by one. next will return false when we try to read beyond the end of the array, but we ignore that and wait for current to notice that there is no current element to stop the loop.
Now, having written all of that, there really isn't any reason to do jump through all these hoops, since PHP has the built-in foreach construct which allows you to iterate over each of an arrays elements, regardless of key type:
foreach($dinner as $key => $value) {
echo "The element in key '" . $key . "' is '" . $value ."'. <br />";
}
This is why I'm assuming this is a homework assignment, since you would probably never have reason to jump through these hoops in a production environment. It is, however, good to know that such constructs exist. For example, if you could use any loop but a foreach, then it would be a lot simpler to just use a while loop than to try to bash a for loop into doing what you want:
reset($dinner);
while (list($key, $value) = each($dinner)) {
echo "The value of '" . $key . "' is '" . $value . "'.<br />";
}
In summary, to iterate over a multidimensional array with associative keys, you would need to nest loops inside each other as shown in the answer to the first question, using one of the loops shown in the answer to the second question to iterate over the associative key values. I'll leave the actual implementation as an exercise for the reader.
To print the values of a array, you can use the print_r function:
print_r($array);
This saves a for-loop.
Just use the handy function print_r
print_r($myarray);
If you don't want to use the print_r function, then for a true n-dimensional array solution:
function array_out($key, $value, $n) {
// Optional Indentation
for($i=0; $i < $n; $i++)
echo(" ");
if(!is_array($value)) {
echo($key . " => " . $value . "<br/>");
} else {
echo($key . " => <br/>");
foreach($value as $k => $v)
array_out($k, $v, $n+1);
}
}
array_out("MyArray", $myArray, 0);
Not sure if its possible to do with a for loop and mixed associative arrays, but foreach does work just fine.
If you have to do it with a for loop, you want the following:
$count = count($array)
for($i = 0; $i <= $count; $i++)
{
$count2=count($array[$i]);
for($j = 0; $j <= $count2; $j++)
{
print $array[$i][$j] . "<br/>";
}
}
foreach( $array as $row ) {
$values = array_values($row);
foreach( $values as $v ) {
echo "$v<br>";
}
}
Should output:
willy
12:04:2011
0
Thomas
13:04:2011
0
$49.00
This will actually be readable:
echo '<pre>';
print_r($myCoolArray);
echo '</pre>';
You would need to do it using something like assigning array_keys to an array, then using a for loop to go through that, etc...
But this is exactly why we have foreach - it would be quicker to write, read and run. Can you explain why it must be done with for?