I have created a session array as follows
$_SESSION['memberInfo']['memberFirstName'] = ($first_name);
$_SESSION['memberInfo']['memberLastName'] = ($surname);
$_SESSION['memberInfo']['hash'] = ($hash);
$_SESSION['memberInfo']['templateSrc'] = ($newTemplateSrc);
in other pages where I'm trying to get the values from the array I have tried foreach and while loops without success, I can see the array in a var_dump
var_dump($_SESSION['memberInfo']);
which shows in console as
array(4) {
["memberFirstName"]=>
string(8) "Geoffrey"
["memberLastName"]=>
string(6) "Turner"
["hash"]=>
string(60) "$2y$10$YBE1tc.BK7yq6bBr/JAlWuN0H8xGdoNSAWzU4/zfd1r3v7jprNBD2"
["templateSrc"]=>
string(61) "../userDirectory/558386500/html/Geoffrey_Turner_558386500.php"
}
in the pages where im trying to itterate the array I have tried using
foreach ($_SESSION['memberInfo'] as $name)
{
$first_name = $name['memberFirstName'];
}
the responce I get shows as
Warning: Illegal string offset 'memberFirstName'
which I believe suggests the itteration is reading an empty array
I can echo out the array using
foreach ($_SESSION['memberInfo'] as $key => $val) {
echo "$key = $val\n";
}
which results in
memberFirstName = Geoffrey
memberLastName = Turner
hash = $2y$10$YBE1tc.BK7yq6bBr/JAlWuN0H8xGdoNSAWzU4/zfd1r3v7jprNBD2
templateSrc = ../userDirectory/558386500/html/Geoffrey_Turner_558386500.php
but for the life of me I cannot seem to figure out how to get each of the array values individually and assign them to a variable
Your foreach makes no sense as you looping an trying to assing single variable too many times for no benefits. So this to be removed:
foreach ($_SESSION['memberInfo'] as $name =) {
$first_name = $name['memberFirstName'];
}
as all you need is:
$first_name = $_SESSION['memberInfo']['memberFirstName'];
how to get each of the array values individually and assign them to a variable
You can use extract which extracts each value and assigns it to a variable.
extract($_SESSION['memberInfo']) this should create the following variables
$memberFirstName, $memberLastName, $hash, $templateSrc
Here is a demo http://ideone.com/XYpC7n
Related
How to get single element from this?
array(1) { [0]=> object(stdClass)#3 (2) { ["id"]=> int(29595) ["image_id"]=> string(20) "eohsidatfx8wyw5ltzt6" } }
I need to separate "image_id". How to do it? I tried
echo $result["image_id"]
but it doesn't work:
Notice: Undefined index: image_id in C:\xampp\htdocs\IGDB\moje\index.php on line 53
It seems your array only directly contains object(stdClass)#3. This object is itself an array containing id and image_id. You can access image_id by doing
echo $result[0]["image_id"];
Ok, got it.
$result3=array_column($result2, 'image_id');
echo $result3[0];
$myArray = array(
'#3' => array (
"id"=> 29595,
"image_id"=> "eohsidatfx8wyw5ltzt6"
)
);
what you are looking for is in the second level of your array.
Use a foreach loop to iterate of the arrays key/value pairs.
foreach($myArray as $value){
foreach($value as $key => $id){
if($key === 'image_id'){
$output = $id;// output now holds the vlaue of the key set with 'image_id'
}
}
}
If you know the value of the key, you can also access this by using the keys like so: $arrayname['firstlevelkey']['secondlevelkey'];
Notice: Undefined index: image_id in C:\xampp\htdocs\IGDB\moje\index.php on line 53
--> This is because you are defining an array with a key that does not exist in the array
echo $result["image_id"] --> here you are telling php that "image_id" is on the first level of the array, however, it looks to be nested in the second layer of the array you are trying to parse. $result['#3']['image_id'].
If you are not sure, write a conditional that looks in the first array using is_array(), if the first is a key value holding a child array. Then run the foreach loop again to look for the key/pair value.
foreach($arr as $values){
// do something if value is string
if(is_array($values){
foreach($values as $key => $value){
// check your second level $key/$value
}
}
}
From WP_Query I am dumping strings stored into separate arrays:
array(1) {
[0]=>
string(8) "Portugal"
}
array(1) {
[0]=>
string(5) "Spain"
}
array(1) {
[0]=>
string(5) "Italy"
}
array(1) {
[0]=>
string(6) "Monaco"
}
array(1) {
[0]=>
string(5) "Spain"
}
array(1) {
[0]=>
string(9) "Lithuania"
}
I am trying to merge those arrays into one array, delete repetitive strings like "Spain" and get the number of unique values.
I was trying to use array_merge():
$tester = array();
foreach($array_string as $value) {
array_merge($tester, $value);
}
$result = array_unique($tester);
print_r($result);
But without any decent results, error telling that <b>Warning</b>: array_merge(): Argument #2 is not an array Could someone tell where I am missing the point? Many thanks for all possible help, will be looking forward.
The code posted in the question is almost good. The intention is correct but you missed out a simple thing: you initialize $tester with an empty array and then never add something to it. In the end, it is still empty and array_unique() has nothing to do but return an empty array too.
The error is in the line:
array_merge($tester, $value);
array_merge() does not change the arrays passed to it as argument. It returns a new array that your code ignores (instead of saving it into $tester).
This is how your code should look like:
$tester = array();
foreach($array_string as $value) {
$tester = array_merge($tester, $value);
}
$result = array_unique($tester);
print_r($result);
Solution #2
You can use call_user_func_array() to invoke array_merge() and pass the values of $array_string as arguments. The returned array contains duplicates; passing it to array_unique() removes them:
$result = array_unique(call_user_func_array('array_merge', $array_string));
Solution #3
A simpler (and possibly faster) way to accomplish the same thing is to use array_column() to get the values into an array and then pass it to array_unique(), of course:
$result = array_unique(array_column($array_string, 0));
This solution works only with PHP 5.5 or newer (the array_column() function doesn't exist in older versions.)
To get the number of unique strings in the merged array you will have to set empty array before WP_Query
$tester = array();
Than inside while loop of WP_Query every string is put into separate array and pushed to $tester
foreach((array)$array_string as $key=>$value[0]) {
array_push($tester,$value);
}
Unique values in array $tester is found using array_unique() functions that should be placed after WP_Query while loop.
$unique_array_string = array_unique($tester, SORT_REGULAR);
$unique_string_number = sizeof($unique_array_string);
You will create an array and will take key of the array for cities names like spain..etc And it will give different cities name always...
$data= array();
$data1 = array("Portugal");
$data2 = array("Spain");
$data3 = array("Italy");
$data4 = array("Monaco");
$data5 = array("Spain");
$data6 = array("Lithuania");
$merge = array_merge($data1, $data2,$data3,$data4,$data5,$data6);
$data = array();
foreach($merge as $value) {
$data[$value] = $value;
}
echo '<pre>',print_r($data),'</pre>';
I got a problem, I got a array from a sql query and I want to associate each value of this array to an index value.
array(16) { ["noCommande"]=> string(5) "49083" ["dateCommande"]=> string(19) "2007-02-21 18:24:04" ...
So here I just want to get back each value one per one. The array[i] doesn't work so I am a bit in trouble.
Thanks you for your support.
It's associative array, values are in
$array['noCommande'];
$array['dateCommande'];
etc.
If you want to ake a loop over array and write all values,
foreach ($array as $key => $value) {
echo $key . ': ' . $value; // echoes 'noCommande: 49083', etc.
}
You can iterate like below:-
foreach($your_array as $key=>$value){
echo $key.'-'.$value;
echo "<br/>";//for new line to show in a good manner
}
It will output like :- noCommande - 49083 and etc.
I am trying to add an array to an existing array. I am able to add the array using the array_push . The only problem is that when trying to add array that contains an array keys, it adds an extra array within the existing array.
It might be best if I show to you
foreach ($fields as $f)
{
if ($f == 'Thumbnail')
{
$thumnail = array('Thumbnail' => Assets::getProductThumbnail($row['id'] );
array_push($newrow, $thumnail);
}
else
{
$newrow[$f] = $row[$f];
}
}
The fields array above is part of an array that has been dynamically fed from an SQl query it is then fed into a new array called $newrow. However, to this $newrow array, I need to add the thumbnail array fields .
Below is the output ( using var_dump) from the above code. The only problem with the code is that I don't want to create a seperate array within the arrays. I just need it to be added to the array.
array(4) { ["Product ID"]=> string(7) "1007520"
["SKU"]=> string(5) "G1505"
["Name"]=> string(22) "150mm Oval Scale Ruler"
array(1) { ["Thumbnail"]=> string(77) "thumbnails/products/5036228.jpg" } }
I would really appreciate any advice.
All you really want is:
$newrow['Thumbnail'] = Assets::getProductThumbnail($row['id']);
You can use array_merge function
$newrow = array_merge($newrow, $thumnail);
Alternatively, you can also assign it directly to $newrow:
if ($f == 'Thumbnail')
$newrow[$f] = Assets::getProductThumbnail($row['id']);
else
...
Or if you want your code to be shorter:
foreach($fields as $f)
$newrow[$f] = ($f == 'Thumbnail')? Assets::getProductThumbnail($row['id']) : $row[$f];
But if you're getting paid by number of lines in your code, don't do this, stay on your code :) j/k
I have an array that I want on multiple pages, so I made it a SESSION array. I want to add a series of names and then on another page, I want to be able to use a foreach loop to echo out all the names in that array.
This is the session:
$_SESSION['names']
I want to add a series of names to that array using array_push like this:
array_push($_SESSION['names'],$name);
I am getting this error:
array_push() [function.array-push]:
First argument should be an array
Can I use array_push to put multiple values into that array? Or perhaps there is a better, more efficient way of doing what I am trying to achieve?
Yes, you can. But First argument should be an array.
So, you must do it this way
$_SESSION['names'] = array();
array_push($_SESSION['names'],$name);
Personally I never use array_push as I see no sense in this function. And I just use
$_SESSION['names'][] = $name;
Try with
if (!isset($_SESSION['names'])) {
$_SESSION['names'] = array();
}
array_push($_SESSION['names'],$name);
$_SESSION['total_elements']=array();
array_push($_SESSION['total_elements'], $_POST["username"]);
Yes! you can use array_push push to a session array and there are ways you can access them as per your requirement.
Basics:
array_push takes first two parameters array_push($your_array, 'VALUE_TO_INSERT');.
See: php manual for reference.
Example:
So first of all your session variable should be an array like:
$arr = array(
's_var1' => 'var1_value',
's_var2' => 'var2_value'); // dummy array
$_SESSION['step1'] = $arr; // session var "step1" now stores array value
Now you can use a foreach loop on $_SESSION['step1']
foreach($_SESSION['step1'] as $key=>$value) {
// code here
}
The benefit of this code is you can access any array value using the key name for eg:
echo $_SESSION[step1]['s_var1'] // output: var1_value
NOTE: You can also use indexed array for looping like
$arr = array('var1_value', 'var1_value', ....);
BONUS:
Suppose you are redirected to a different page
You can also insert a session variable in the same array you created. See;
// dummy variables names and values
$_SESSION['step2'] = array(
's_var3' => 'page2_var1_value',
's_var4' => 'page2_var2_value');
$_SESSION['step1step2'] = array_merge($_SESSION['step1'], $_SESSION['step2']);
// print the newly created array
echo "<pre>"; // for formatting printed array
var_dump($_SESSION['step1step2']);
echo "<pre>";
OUTPUT:
// values are as per my inputs [use for reference only]
array(4) {
["s_var1"]=>
string(7) "Testing"
["s_var2"]=>
int(4) "2124"
["s_var3"]=>
int(4) "2421"
["s_var4"]=>
string(4) "test"
}
*you can use foreach loop here as above OR get a single session var from the array of session variables.
eg:
echo $_SESSION[step1step2]['s_var1'];
OUTPUT:
Testing
Hope this helps!
Try this, it's going to work :
session_start();
if(!isset($_POST["submit"]))
{
$_SESSION["abc"] = array("C", "C++", "JAVA", "C#", "PHP");
}
if(isset($_POST["submit"]))
{
$aa = $_POST['text1'];
array_push($_SESSION["abc"], $aa);
foreach($_SESSION["abc"] as $key => $val)
{
echo $val;
}
}
<?php
session_start();
$_SESSION['data']= array();
$details1=array('pappu','10');
$details2=array('tippu','12');
array_push($_SESSION['data'],$details1);
array_push($_SESSION['data'],$details2);
foreach ($_SESSION['data'] as $eacharray)
{
while (list(, $value) = each ($eacharray))
{
echo "Value: $value<br>\n";
}
}
?>
output
Value: pappu Value: 10 Value: tippu Value: 12