Array ( [0] => UK [1] => France [2] => USA ) in these array get only values
like array(UK, France, USA) am trying like below,
$expression=array_values(array('0' => 'UK', '1' => 'France', '2' => 'USA'));
var_dump($expression);
OUTPUT PLAN:
array(3) { [0]=> string(2) "UK" [1]=> string(6) "France" [2]=> string(3) "USA" }
Can i get my desired output?
Please read answer carefully.
$arr = array('UK', 'France', 'USA'); // It has 0 ,1 ,2 keys but you cannot see in the code`
But in browser you can see it.
array(3) { [0]=> string(2) "UK" [1]=> string(6) "France" [2]=> string(3) "USA" }
Just use loop to print each country
foreach($arr as $country){
echo $country."<br>";
}
You can understand it by below loop
foreach($arr as $k=>$country){
echo "$k => $country"."<br>"; // Here $k is key like 0,1,2..
}
If you have array like below:-
$arr = array('uk'=>'UK', 'france'=>'France', 'usa'=>'USA') // It has uk ,france ,usa keys
now array_values($arr) will give you output as below
array(3) { [0]=> string(2) "UK" [1]=> string(6) "France" [2]=> string(3) "USA" }
It will remove all keys and regenerate index of key from 0.
Refer below links to understand PHP array:-
Link1
Link2
Link3
Hope it will help you :)
You could just do:
$out = array();
foreach($old_array as $new_value) { //Where $old_array is the array you want to convert
array_push($out, $new_value);
}
All PHP arrays have an internal index whether you attach one or not. So in your example even if you created an array using $countries = array("USA", "UK", "France") it would still output with indexes.
You can however ignore the indexes when your looping through it and only work with the values using a foreach() loop.
An example of such a loop would be...
foreach($expression as $index => $country) {
echo($country . "<br />");
};
The above example will print each country on its own line. You can adapt it to suit whatever looping you need.
As a side note be aware that the index will commence from 0 so item 1 in the array will have an index of 0 and increment from there.
You have this array.
Array ( [0] => UK [1] => France [2] => USA )
you have key and value assigned to it.
if you make another array like
array('UK','France','USA')
It is an associative array. Its the same as above.
Read it for more info
If you want to do operation with the array you can use foreach and for or other array related functions. So, first of all say what are you trying to accomplish with this one.
$expression=array_values(array('0' => 'UK', '1' => 'France', '2' => 'USA'));
foreach($expression as $val) {
echo $val.",";
}
Related
I have to extract strings from a xml file. One particular value has been generated using json enconding.
Here is a exemple of what I can find:
<plus_details>
[["Neuf"],["Petite copropri\u00e9t\u00e9"],["Vue mer"]]
</plus_details>
I would like to extract the strings and display them inline and separated by commas, like this :
Neuf, Petite copropriété, Vue mer
I tried using json_decode function, but the only thing I can display is:
array(3) {
[0]=>
array(1) {
[0]=>
string(4) “Neuf”
}
[1]=>
array(1) {
[0]=>
string(20) “Petite copropriété”
}
[2]=>
array(1) {
[0]=>
string(7) “Vue mer”
}
}
Any help would be appreciated. Thanks.
Simple use a loop to go through your data. When you json_decode the string you provided us, you will end-up with an array like this :
Array
(
[0] => Array
(
[0] => Neuf
)
[1] => Array
(
[0] => Petite copropriété
)
[2] => Array
(
[0] => Vue mer
)
)
So in order to get your data you need to loop your array.
foreach(json_decode($json) as $data){
echo $data[0];
echo '<br>';
}
The output of the above code is:
Neuf
Petite copropriété
Vue mer
Here's the idea: a user enters his ZIP code.
Based on the inserted ZIP code, I get an array of ZIP codes (distance ordered).
Next I want to order an existing array of ZIP codes based on the distance ordered array.
So basically I have two arrays:
Array which should be ordered
array(2) {
[0]=>
string(4) "2018"
[1]=>
string(4) "2500"
}
Distance ordered array
array(247) {
[0]=>
string(4) "2000"
[1]=>
string(4) "2500"
[2]=>
string(4) "2050"
[2]=>
string(4) "2018"
In this example, my array (number 1) should be ordered like so: [0] => 2500, [1] => 2018
How can I manage this?
You could use array_intersect() to get only the values of the second array that are also in the first array. And as the function preserves the keys - and so the order -, you only have to renumber them.
$a1=array(2018,2500);
$a2=array(2000,2500,2050,2018);
$a3=array_intersect( $a2 , $a1 );
echo print_r($a3,true);
Result:
Array (
[1] => 2500
[3] => 2018 )
I am getting a Json respond with :
$response = curl_exec($rest);
$json = json_decode($response, true);
I manage to get its values(strings) with :
$foundUserId=$json['results'][0]['userId'];
$foundName=$json['results'][0]['name'];
$foundPhoneNum=$json['results'][0]['phoneNumber'];
But the last value- phoneNumber, is array of strings .
If i try then to loop over it i get nothing(although the array is there in the Json)
foreach ($foundPhoneNum as &$value)
{
print_r($value);
}
What am i doing wrong ?
EDIT :
The json:
Array ( [results] => Array ( [0] => Array ( [action] => message [createdAt] => 2015-11-21T09:36:33.620Z [deviceId] => E18DDFEC-C3C9 [name] => me [objectId] => klMchCkIDi [phoneNumber] => ["xx665542","xxx9446"] [state] => 1 [updatedAt] => 2015-11-22T08:24:46.948Z [userId] => 433011AC-228A-4931-8700-4D050FA18FC1 ) ) )
You might have json as a string inside json. That's why after json_decode() you still have json inside phoneNumber. You have 2 options:
Decode phoneNumber like
$foundPhoneNum=json_decode($json['results'][0]['phoneNumber']);
Build proper initial json. Instead of
{"phoneNumber": "[\"xx665542\",\"xxx9446\"]"}
should be
{"phoneNumber": ["xx665542","xxx9446"]}
There's a couple of ways to debug situations like this as mentioned in the comments; print_r() and var_dump().
var_dump(), although harder to read the first few times, is my favourite because it tells you the data types of each value in the array. This will confirm whether or not the expected string is indeed an array.
An example from the var_dump() documentation:
<?php
$a = array(1, 2, array("a", "b", "c"));
var_dump($a);
And the output is;
array(3) {
[0]=>
int(1)
[1]=>
int(2)
[2]=>
array(3) {
[0]=>
string(1) "a"
[1]=>
string(1) "b"
[2]=>
string(1) "c"
}
}
As you can see it shows array, int and string as the data types.
You might also like to install the Xdebug extension for PHP which dumps more useful error messages and tracebacks. Again harder to read the first few times, but well worth it!
foreach ($foundPhoneNum as $value)
{
print_r($value);
}
There was an extra & before $value. Try this.
I have to insert some data from an excel document into the database.
The data has been saved as .csv and then added into an array through PHP.
The data look like:
Column A Column B Column C
100 200 100
50 10 100
200 200 100
30 10 300
Then I use this to separate each columns (within a foreach loop)
list( $columnA, $columnB) = explode( ',', $values[0] );
$columnA= array($columnA);
print_r($columnA);
The above code prints the values of each column.
So I'm trying to find a way to remove duplicates from each column and then from each row (no matter what the column name is). I want to remove duplicates from the whole document. For the data I posted for example I just need the values 100,200,50,10,30,300 (only the unique values from the whole doc).
UPDATE:
What the original array (the one I've created by using for loop and passing all data from .CSV file) shows:
Array ( [0] => G2100,100%,,,,,,,,,200,0.24,77,51,2,47, )
Array ( [0] => G2101,100%,,,,,,,,,200,0.24,77,42,15,43, )
Array ( [0] => G2102,30%,,,,,,,,,200,0.24,77,38,25,37, )
So by using the list function I mentioned before I split all columns and get the values for each column. THEN if i print $columnB array for example it shows this:
Array ( [0] => 100%) Array ( [0] => 100%) Array ( [0] => 30%)
and so on. When I use unique_array it does nothing.
$columnB = array_unique($columnB, SORT_REGULAR);
I tried to use array_map but it doesn't work either.
Any help would be much appreciated.
I don't understand why does array_unique not works in your case, because actually it solves the problem:
<?php
$columnA = array(50,50,200,10);
$columnB = array(100,50,200,100);
$columnC = array(150,50,250);
$merged = array_merge($columnA, $columnB, $columnC);
$result = array_unique($merged);
var_dump($result);
?>
And output is:
array(6) {
[0]=>
int(50)
[2]=>
int(200)
[3]=>
int(10)
[4]=>
int(100)
[8]=>
int(150)
[10]=>
int(250)
}
This is an trivial example, but if you can manage that your inputs are like arrays above, then you can use array_unique to have only unique values...
EDIT 1:
To remove % sign from string just use rtrim where is needed:
$string = '100%';
$trimmed = (int)rtrim($string,'%');//make it int(or float if you like)
var_dump($trimmed);
EDIT 2:
Related to looping through arrays:
//I suppose this
//Array ( [0] => 100%) Array ( [0] => 100%) Array ( [0] => 30%)
//maps to this
$columnA = array(
0=>array('100%'),
1=>array('100%'),
2=>array('30%')
);
//go through every element
$temp = array();
foreach($columnA as $subArray){
//in this case when we know that there is only one element in the array we can do next:
$temp[] = $subArray[0];
}
$result = array_unique($temp);
echo "<pre>";
var_dump($result);
echo "</pre>";
And this would be the output:
array(2) {
[0]=>
string(4) "100%"
[2]=>
string(3) "30%"
}
I have an sorted array which contains first names of people.
This array has lots of names which are same.
I want to output only duplicate names.
Example,
input array:
Array
(
[0] => Abbas
[1] => Abhay
[2] => Abhinav
[3] => Abhishek
[4] => Aditya
[5] => Ahmed
[6] => Ahmed
[7] => Ajay
[8] => Ajay
}
It should return
Array
(
[5] => Ahmed
[6] => Ahmed
[7] => Ajay
[8] => Ajay
}
Use this code:
# assuming your original array is $arr
array_unique(array_diff_assoc($arr, array_unique($arr)));
It will return unique duplicates but if you want non-unique duplicates then use:
array_diff_assoc($arr, array_unique($arr));
EDIT: Based on your comments, try this code:
$uarr = array_unique($arr);
var_dump(array_diff($arr, array_diff($uarr, array_diff_assoc($arr, $uarr))));
OUTPUT
array(4) {
[5]=>
string(5) "Ahmed"
[6]=>
string(5) "Ahmed"
[7]=>
string(4) "Ajay"
[8]=>
string(4) "Ajay"
}
You could use this function http://php.net/manual/en/function.array-unique.php to get an array withoutt he duplicate values, then you can use this function http://www.php.net/manual/en/function.array-intersect.php to find the differences, maintaining key association.
Try array_reduce:
http://php.net/manual/en/function.array-reduce.php
Create a callback that populates an array using the values from $input as keys, and increments them accordingly. And then filter those that appear more than once.
Using array_count_values() to count up everything in the array, then filter the resulting array to show only the ones where there's more than 1:
$input = array(.... your names here ....);
$counts = array_count_values($input);
$duplicates = array_filter($counts, function element { return ($element > 1) });
Doing that off the top of my head, but should be enough to get you started.