Append field to the end of an array - php

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);

Related

how to make array like this

I have an array in the array, and I want to make it just one array, and I can easily retrieve that data
i have some like
this
but the coding only combines the last value in the first array, not all values
is it possible to make it like that?
so that I can take arrays easily
I would make use of the unpacking operator ..., combined with array_merge:
$array['test2'] = array_merge(...array_merge(...$array['test2']));
In your case you need to flatten exactly twice, if you try to do it one time too much it will fail due to the items being actual arrays themselves (from PHP's perspective).
Demo: https://3v4l.org/npnTi
Use array_merge (doc) and ... (which break array to separate arrays):
function flatten($arr) {
return array_merge(...$arr);
}
$arr = [[["AAA", "BBB"]], [["CCC"]]];
$arr = flatten(flatten($arr)); // using twice as you have double depth
In your case, $arr is $obj["test2"]. If your object is json cast it to array first and if it is a string use json_decode
Live example: 3v4l
if you have a array then you can use the below code
if(!empty($array['test2'])){
$newarray = array();
foreach ($array['test2'] as $arrayRow) {
$newarray = array_merge($newarray,$arrayRow);
}
$array['test2'] = $newarray;
}

Key Value Array From String

I have a key value pair string that I would like to convert to a functional array. So that I can reference the values using their key. Right now I have this:
$Array = "'Type'=>'Honda', 'Color'=>'Red'";
$MyArray = array($Array);
This is not bringing back a functional key/value array. My key value pairs are in a variable string which means the => is part of the string and i think this is where my problem is. Any help would be appreciated. All i am trying to do is convert the string to a functional key/value pair where I can grab the values using the key. My data is in a string so please don't reply with the answer "take them out of the string." I am aware that this will work:
$MyArray = array('Type'=>'Honda', 'Color'=>'Red');
But my probem is that the the data is already in the form of a string. Thank you for any help.
There is no direct way to do this. As such, you'll need to write a custom function to build the keys and values for each element.
An example specification for the custom function:
Use explode() to split each element based on the comma.
Iterate over the result and:
explode() on =>
Remove unnecessary characters, i.e. single quotes
Store the first element as the key and the second element as the value
Return the array.
Note: if your strings contain delimiters this will be more challenging.
You do need to "take them out of the string", as you say. But you don't have to do it manually. The other answer uses explode; that's a fine method. I'll show you another - what I think is the easiest way is to use preg_match_all() (documentation), like this:
$string = "'Type'=>'Honda', 'Color'=>'Red'";
$array = array();
preg_match_all("/'(.+?)'=>'(.+?)'/", $string, $matches);
foreach ($matches[1] as $i => $key) {
$array[$key] = $matches[2][$i];
}
var_dump($array);
You need to parse the string and extract the data:
$string = "'Type'=>'Honda', 'Color'=>'Red'";
$elements = explode(",",$string);
$keyValuePairs = array();
foreach($elements as $element){
$keyValuePairs[] = explode("=>",$element);
}
var_dump($keyValuePairs);
Now you can create your on array using the $keyValuePairs array.
Here is an example of one way you can do it -
$Array = "'Type'=>'Honda', 'Color'=>'Red'";
$realArray = explode(',',$Array); // get the items that will be in the new array
$newArray = array();
foreach($realArray as $value) {
$arrayBit = explode('=>', $value); // split each item
$key = str_replace('\'', '', $arrayBit[0]); // clean up
$newValue = str_replace('\'', '', $arrayBit[1]); // clean up
$newArray[$key] = $newValue; // place the new item in the new array
}
print_r($newArray); // just to see the new array
echo $newArray['Type']; // calls out one element
This could be placed into a function that could be extended so each item gets cleaned up properly (instead of the brute force method shown here), but demonstrates the basics.

Storing array data in foreach loop in PHP

I am wondering how can I store all values from a foreach loop, I know that I am re-initialising in the loop but I'm not sure how to store the data. Heres my basic loop:
$array = array("v1", "v2", "v3", "v4");
foreach($array as $row){
$arr = array('val' => $row);
echo $row;
}
print_r($arr);
So when I use the print_r($arr) the only thing outputted would be v4 and I know that the values are there because the echo $row; does return each output individually.
My question would be how can I store each instance of row in my array?
Create a new array, fill it:
$array = array("v1", "v2", "v3", "v4");
$newArray = array();
foreach($array as $row){
// notice the brackets
$newArray[] = array('val' => $row);
}
print_r($newArray);
It looks like you are storing your array wrong.
Try adjusting the $arr = array('val' => $row);
to:
$arr[] = array('val' => $row);
This will set it so you pick up each line as a separate array which you can easily navigate through.
Hope this helps!
If I'm reading correctly, you want to transform your array from simple values to key-value pairs of 'val'->number. array_map is a concise way of doing this sort of transformation.
$array = array("v1", "v2", "v3", "v4");
$arr = array_map(function($v) { return array('val'=>$v); }, $array);
print_r($arr);
While it doesn't matter in this case, array_map also has the handy feature of preserving your keys, in case that is desired.
Note that you can also provide a named function to array_map, instead of providing the implementation inline, which can be nice in the event that your transform method gets more complicated. More on array_map here.

"Classic" array in php

So, I'm starting a new project and working with php for the first time.
I get that the average definition and functioning of arrays in php is actually pretty much a namevalue combo.
Is there some syntax, API, or other terminology for just a simple list of items?
I.e. inserting something like ['example','example2','example3','example4'] that I can just call based off their index position of the array, without having to go in and modify the syntax to include 0 => 'example', etc...
This is a very shortlived array so im not worried about long term accessibility
php arrays are simple to use. You can insert into an array like:
$array=array('a','b','c'.....);
Or
$array[]="a";
$array[]="b";
$array[]="c";
or
array_push($array, "a");
array_push($array, "b");
array_push($array, "c");
array_push($array, "d");
and call them by their index values:
$array[0];
this will give you a
$yourArray = array('a','b','c');
or
$yourArray[] = 'a';
$yourArray[] = 'b';
$yourArray[] = 'c';
will get you an array with integer index values instead of an associative one..
You still can use array as "classic" arrays in php, just the way you think.
For example :
<?php
$array = array("First", "Second", "Third");
echo $array[1];
?>
You can then add different values <?php $array[] = "Forth"; ?> and it will be indexed in the order you specified it.
Notice that you can still use it as an associative array :
<?php
$array["newValue"] = "Fifth";
$array[1] = "ReplaceTheSecond";
$array[10] = "";
?>
Arrays in PHP can either be based on a key, like 0 or "key" => "value", or values can just be "appended" to the array by using $array[] = 'value'; .
So:
$mine = array();
$mine[] = 'test';
$mine[] = 'test2';
echo $mine[0];
Would produce 'test';
Haven't tested the code.

Combine Two Arrays with numerical keys without overwriting the old keys

I don't want to use array_merge() as it results in i misunderstood that all values with the same keys would be overwritten. i have two arrays
$array1 = array(0=>'foo', 1=>'bar');
$array2 = array(0=>'bar', 1=>'foo');
and would like to combine them resulting like this
array(0=>'foo', 1=>'bar',2=>'bar', 3=>'foo');
array_merge() appends the values of the second array to the first. It does not overwrite keys.
Your example, results in:
Array (
[0] => foo
[1] => bar
[2] => bar
[3] => foo )
However, If the input arrays have the same string keys, then the later value for that key will overwrite the previous one. If, however, the arrays contain numeric keys, the later value will not overwrite the original value, but will be appended.
Unless this was just an example to another problem you were having?
Does this answer your question? I'm not sure exactly what you're trying to accomplish, but from your description it sounds like this will work:
$array1 = array(0=>'foo', 1=>'bar');
$array2 = array(0=>'bar', 1=>'foo');
foreach ($array2 as $i) {
$array1[] = $i;
}
echo var_dump($array1);
If someone stumbles upon this, this is a way to do it nowadays:
var_dump(array_merge_recursive($array1, $array2));
There are probably much better ways but what about:
$newarray= array();
$array1 = array(0=>'foo', 1=>'bar');
$array2 = array(0=>'bar', 1=>'foo');
$dataarrays = array($array1, $array2);
foreach($dataarrays as $dataarray) {
foreach($dataarray as $data) {
$newarray[] = $data;
}
}
print_r($newarray);
$result = array_keys(array_merge(array_flip($array1), array_flip($array2)));
var_dump($result);

Categories