I have an array:
Array
(
[0] => hello;string1
[1] => bye;string2
)
I want to get the array so I have the value of the string (after the ;) to be a value of the array key, so it becomes multi dimensional
$arr = array
(
"hello;string1",
"bye;string2"
);
$newArr = [];
foreach ($arr as $a) {
$e = explode(";", $a);
$newArr[$e[1]] = $e[0];
}
print_r($newArr);
You could do this using an explode
an explode explodes a variable on a delimitter, in your case ;
it puts the exploded values inside an array
<?php
$arr = ['test;hi', 'another;one'];
$newarr = [];
foreach ($arr as $key => $value) {
$value = explode(';', $value);
$newarr[$value[0]] = $value[1];
}
var_dump($newarr);
Output of the var_dump:
array(2) { ["test"]=> string(2) "hi" ["another"]=> string(3) "one" }
$array=Array
(
0 => "hello;string1",
1 => "bye;string2"
);
$result=array();
foreach($array as $data)
{
list($value,$key)=explode(";", $data);
$result[$key]=$value;
}
print_r($result);
Thanks for all your help, this actually what i wanted, sorry for being vague
foreach ($arr as $a) {
$e = explode(";", $a);
$newarr[] = array('hello' => $e[0], 'bye' => $e[1]);
}
You should use something like this!!
$cars = array
(
array("Volvo",22,18),
array("BMW",15,13),
array("Saab",5,2),
array("Land Rover",17,15)
);
for ($row = 0; $row < 4; $row++) {
echo "<p><b>Row number $row</b></p>";
echo "<ul>";
for ($col = 0; $col < 3; $col++) {
echo "<li>".$cars[$row][$col]."</li>";
}
echo "</ul>";
}
Outout
Row number 0
Volvo
22
18
Row number 1
BMW
15
13
Row number 2
Saab
5
2
Row number 3
Land Rover
17
15
I fixed my answer to the new code above also you can find it here at https://www.w3schools.com/php/php_arrays_multi.asp
Related
$tag=[25, 26];
$tagarray[]=[25,29,30,44,26];
I need a result of [29,30,44]. Here my main array is tagarray. and tested it with tag array. I need unmatched values from tagarray without any array function like array_diff().I want to compare both arrays and only provide the elements from tagarray which are not present in tag array.
$missings = [];
$matches = false;
for ( $i = 0; $i < count($tagarray); $i++ ) {
$matches = false;
for ($e = 0; $e < count($tag); $e++ ) {
if ( $tagarray[$i] == $tag[$e] ) $matches = true;
}
if(!$matches) array_push($missings,$tagarray[$i]);
}
dd($missings);
You need nested for loops to loop over each element of your array to filter, and for each of these elements, loop on the array containing the filters.
Since you do not want to use any of the array function, you need to use a boolean to check whether or not the index was to be filtered or not and make use of a 3rd array to store the filtered array.
Take a look:
$tag = [25, 26];
$tagarray = [25,29,30,44,26];
$filteredArray = [];
for($i = 0; $i < count($tagarray); ++$i){
$toRemove = false;
for($j = 0; $j < count($tag); ++$j){
if($tagarray[$i] == $tag[$j]){
$toRemove = true;
break;
}
}
if(!$toRemove){
$filteredArray[] = $tagarray[$i];
}
}
var_dump($filteredArray);
Output
array(3) {
[0]=>
int(29)
[1]=>
int(30)
[2]=>
int(44)
}
I would personally not choose this solution and go with Aksen's one, but since you do not want to use any array functions I assume that this is a school assignment and that you have no other choices ;)
If you don't want to use array_diff() then you can use in_array():
$res = [];
foreach($tagarray[0] as $val){
if (!in_array($val,$tag)) $res[] = $val;
}
print_r($res);
Output:
Array
(
[0] => 29
[1] => 30
[2] => 44
)
Demo
If $tagarray has more then 1 element:
$tag=[25, 26];
$tagarray[]=[25,29,30,44,26];
$tagarray[]=[25,22,11,44,26];
$res = [];
foreach($tagarray as $ind=>$tagar){
foreach($tagar as $val){
if (!in_array($val,$tag)) $res[$ind][] = $val;
}
}
Output:
Array
(
[0] => Array
(
[0] => 29
[1] => 30
[2] => 44
)
[1] => Array
(
[0] => 22
[1] => 11
[2] => 44
)
)
Demo
Third Without any inbuilt PHP array function:
$tagar_l = count($tagarray);
$tag_l = count($tag);
$tagar_0_l = count($tagarray[0]);
$res = [];
for($i = 0; $i<$tagar_l; $i++){
$res[] = $tagarray[$i];
for($j = 0; $j<$tagar_0_l; $j++){
for($k = 0; $k<$tag_l; $k++){
if ($tag[$k] === $tagarray[$i][$j]) unset($res[$i][$j]);
}
}
sort($res[$i]);
}
Demo
Via foreach loop:
$res = [];
foreach($tagarray as $ind=>$arr){
$res[] = $arr;
foreach($arr as $ind_a=>$val){
foreach($tag as $comp){
if ($comp === $val) unset($res[$ind][$ind_a]);
}
}
sort($res[$ind]);
}
Demo
Here i want to find unique values,so i am writing code like this but i can't get answer,for me don't want to array format.i want only string
<?php
$array = array("kani","yuvi","raja","kani","mahi","yuvi") ;
$unique_array = array(); // unique array
$duplicate_array = array(); // duplicate array
foreach ($array as $key=>$value){
if(!in_array($value,$unique_array)){
$unique_array[$key] = $value;
}else{
$duplicate_array[$key] = $value;
}
}
echo "unique values are:-<br/>";
echo "<pre/>";print_r($unique_array);
echo "duplicate values are:-<br/>";
echo "<pre/>";print_r($duplicate_array);
?>
You can use array_unique() in single line like below:-
<?php
$unique_array = array_unique($array); // get unique value from initial array
echo "<pre/>";print_r($unique_array); // print unique values array
?>
Output:- https://eval.in/601260
Reference:- http://php.net/manual/en/function.array-unique.php
If you want in string format:-
echo implode(',',$final_array);
Output:-https://eval.in/601261
The way you want is here:-
https://eval.in/601263
OR
https://eval.in/601279
I am baffled by your selection as the accepted answer -- I can't imagine how it can possibly satisfy your requirements.
array_count_values() has been available since PHP4, so that is the hero to call upon here.
Code: (Demo)
$array = array("kani","yuvi","raja","kani","mahi","yuvi") ;
$counts = array_count_values($array); // since php4
foreach ($counts as $value => $count) {
if ($count == 1) {
$uniques[] = $value;
} else {
$duplicates[] = $value;
}
}
echo "unique values: " , implode(", ", $uniques) , "\n";
echo "duplicate values: " , implode(", ", $duplicates);
Output:
unique values: raja, mahi
duplicate values: kani, yuvi
To get unique values from array use array_unique():
$array = array(1,2,1,5,10,5,10,7,9,1) ;
array_unique($array);
print_r(array_unique($array));
Output:
Array
(
[0] => 1
[1] => 2
[3] => 5
[4] => 10
[7] => 7
[8] => 9
)
And to get duplicated values in array use array_count_values():
$array = array(1,2,1,5,10,5,10,7,9,1) ;
print_r(array_count_values($array));
Output:
Array
(
[1] => 3 // 1 is duplicated value as it occurrence is 3 times
[2] => 1
[5] => 2 // 5 is duplicated value as it occurrence is 3 times
[10] => 2 // 10 is duplicated value as it occurrence is 3 times
[7] => 1
[9] => 1
)
<?php
$arr1 = [1,1,2,3,4,5,6,3,1,3,5,3,20];
print_r(arr_unique($arr1)); // will print unique values
echo "<br>";
arr_count_val($arr1); // will print array with duplicate values
function arr_unique($arr) {
sort($arr);
$curr = $arr[0];
$uni_arr[] = $arr[0];
for($i=0; $i<count($arr);$i++){
if($curr != $arr[$i]) {
$uni_arr[] = $arr[$i];
$curr = $arr[$i];
}
}
return $uni_arr;
}
function arr_count_val($arr) {
$uni_array = arr_unique($arr1);
$count = 0;
foreach($uni_array as $n1) {
foreach($arr as $n1) {
if($n1 == $n2) {
$count++;
}
}
echo "$n1"." => "."$count"."<br>";
$count=0;
}
}
?>
I have an array that looks something like this:
Array (
[0] => Array ( [country_percentage] => 5 %North America )
[1] => Array ( [country_percentage] => 0 %Latin America )
)
I want only numeric values from above array. I want my final array like this
Array (
[0] => Array ( [country_percentage] => 5)
[1] => Array ( [country_percentage] => 0)
)
How I achieve this using PHP?? Thanks in advance...
When the number is in first position you can int cast it like so:
$newArray = [];
foreach($array => $value) {
$newArray[] = (int)$value;
}
I guess you can loop the 2 dimensional array and use a preg_replace, i.e.:
for($i=0; $i < count($arrays); $i++){
$arrays[$i]['country_percentage'] = preg_replace( '/[^\d]/', '', $arrays[$i]['country_percentage'] );
}
Ideone Demo
Update Based on your comment:
for($i=0; $i < count($arrays); $i++){
if( preg_match( '/North America/', $arrays[$i]['country_percentage'] )){
echo preg_replace( '/[^\d]/', '', $arrays[$i]['country_percentage'] );
}
}
Try this:
$arr = array(array('country_percentage' => '5 %North America'),array("country_percentage"=>"0 %Latin America"));
$result = array();
foreach($arr as $array) {
$int = filter_var($array['country_percentage'], FILTER_SANITIZE_NUMBER_INT);
$result[] = array('country_percentage' => $int);
}
Try this one:-
$arr =[['country_percentage' => '5 %North America'],
['country_percentage' => '0 %Latin America']];
$res = [];
foreach ($arr as $key => $val) {
$res[]['country_percentage'] = (int)$val['country_percentage'];
}
echo '<pre>'; print_r($res);
output:-
Array
(
[0] => Array
(
[country_percentage] => 5
)
[1] => Array
(
[country_percentage] => 0
)
)
You can use array_walk_recursive to do away with the loop,
passing the first parameter of the callback as a reference to modify the initial array value.
Then just apply either filter_var or intval as already mentioned the other answers.
$array = [
["country_percentage" => "5 %North America"],
["country_percentage" => "0 %Latin America"]
];
array_walk_recursive($array, function(&$value,$key){
$value = filter_var($value,FILTER_SANITIZE_NUMBER_INT);
// or
$value = intval($value);
});
print_r($array);
Will output
Array
(
[0] => Array
(
[country_percentage] => 5
)
[1] => Array
(
[country_percentage] => 0
)
)
You could get all nemeric values by looping through the array. However I don't think this is the most efficient and good looking answer, I'll post it anyways.
// Array to hold just the numbers
$newArray = array();
// Loop through array
foreach ($array as $key => $value) {
// Check if the value is numeric
if (is_numeric($value)) {
$newArray[$key] = $value;
}
}
I missunderstood your question.
$newArray = array();
foreach ($array as $key => $value) {
foreach ($value as $subkey => $subvalue) {
$subvalue = trim(current(explode('%', $subvalue)));
$newArray[$key] = array($subkey => $subvalue);
}
}
If you want all but numeric values :
$array[] = array("country_percentage"=>"5 %North America");
$array[] = array("country_percentage"=>"3 %Latin America");
$newArray = [];
foreach ($array as $arr){
foreach($arr as $key1=>$arr1) {
$newArray[][$key1] = intval($arr1);
}
}
echo "<pre>";
print_R($newArray);
This is kind of a ghetto method to doing it cause I love using not as many pre made functions as possible. But this should work for you :D
$array = array('jack', 2, 5, 'gday!');
$new = array();
foreach ($array as $item) {
// IF Is numeric (each item from the array) will insert into new array called $new.
if (is_numeric($item)) { array_push($new, $item); }
}
I want to put my string (separated by comma) in 2 different arrays.
$str = 1,First,2,Second,3,Third,4,Forth,5,Fifth
My goal is to group the numbers and the text.
$number = {1,2,3,4,5)
$text = {first, second, third, forth, fifth}
I tried to use explode(), but I only be ale to create a single array.
This should work for you:
First explode() your string by a comma. Then you can array_filter() the numbers out. And at the end you can simply take the array_diff() from the $arr and the $numbers array.
<?php
$str = "1,First,2,Second,3,Third,4,Forth,5,Fifth";
$arr = explode(",", $str);
$numbers = array_filter($arr, "intval");
$text = array_diff($arr, $numbers);
?>
You can use explode() and array_map() over the results:
$str = '1,First,2,Second,3,Third,4,Forth,5,Fifth';
array_map(function($item) use (&$numbers, &$strings) {
if(is_numeric($item)) {
$numbers []= $item;
} else {
$strings []= $item;
}
}, explode(',', $str));
var_dump($numbers, $strings);
<?php
$str = array(1,'First',2,'Second',3,'Third',4,'Forth',5,'Fifth');
$letters =array();
$no = array();
for($i=0;$i<count($str);$i++){
if($i%2 ==0){
$letters[] = $str[$i];
}else{
$no[] = $str[$i];
}
}
print_r($no);
print_r($letters);
?>
May be this can help you
$str = '1,First,2,Second,3,Third,4,Forth,5,Fifth';
$array = explode(',',$str);
$number = array();
$string = array();
foreach($array as $val)
{
if(is_numeric($val))
{
$number[] = $val;
}
elseif(!is_numeric($val))
{
$string[] = $val;
}
}
echo $commNum = implode(',',$number); // These are strings
echo '<br/>'.$commStr = implode(',',$string); // These are strings
echo '<pre>';
print_r($number); // These are arrays
echo '<pre>';
print_r($string); // These are arrays
This should work for you.
$str = '1,First,2,Second,3,Third,4,Forth,5,Fifth';
$result = explode(',',$str);
$number = array();
$text = array();
foreach(explode(',',$str) as $key => $value){
if($key % 2 == 1){
$text[] = $value;
}elseif($key % 2 == 0){
$number[] = $value;
}
}
print_r($number);//Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 )
print_r($text);//Array ( [0] => First [1] => Second [2] => Third [3] => Forth [4] => Fifth )
and if your array is not consistent in this manner then some of these above answers are well suited for you like of Rizier123,hek2mgl,& Sunil's one
I'm updating my answer for your correspondent comments over Adrian
foreach(explode(',',$str) as $key => $value){
if(is_numeric($value)){
$number[] = $value;
}else{
$text[] = $value;
}
}
You can use explode, but you need apply some filter in this case is is_numeric:
<?php
$str = '1,First,2,Second,3,Third,4,Forth,5,Fifth, erewwrw , 6 ';
$array = explode(',', $str);
$array_numbers = array();
$array_letters = array();
for($i = 0; $i < count($array); $i++) {
if(is_numeric(trim($array[$i]))) {
$array_numbers[] = trim($array[$i]);
} else {
$array_letters[] = trim($array[$i]);
}
}
print_r($array_numbers);
print_r($array_letters);
?>
Output:
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
)
Array
(
[0] => First
[1] => Second
[2] => Third
[3] => Forth
[4] => Fifth
)
Assuming that your string contains number followed by string and so on,
following should be the solution.
Create two blank arrays: $numbers and $strings.
Just loop over the array and get even and odd elements.
Even elements should go to numbers array and odd elements should go to strings array.
$str = '1,First,2,Second,3,Third,4,Forth,5,Fifth';
$numbers = array();
$strings = array();
$temp = explode(',', $str);
$i=0;
foreach ($temp as $e) {
if ($i%2) {
$strings[] = $e;
}
else {
$numbers[] = $e;
}
++$i;
}
echo '<pre>';
print_r($numbers);
echo '</pre>';
echo '<pre>';
print_r($strings);
echo '</pre>';
I have in a database table 3 rows that are json data and i want them merge they in a array, how can fix it?
Row 1 : ["11,22,13"]
Row 2 : ["48"]
Row 3 : ["53,67,70"]
I want in output as: array(11,22,13,48,53,67,70)
My tried as:
$result = $this->db->get_where('table',array('mainpage'=>$mp'));
$data = array();
foreach($result->result() as $row){
$dv = json_decode($row->sbouy);
$out = array();
foreach($dv as $idx => $val){
$out[] = $val;
}
echo '<pre>';
print_r($out); // This is not what I want output
}
In my code output is as(This is not what I want output):
Array
(
[0] => 11,22,13
)
Array
(
[0] => 48
)
Array
(
[0] => 53,67,70
)
Use this
$data = array();
$out = array();
foreach($result->result() as $row){
$dv = json_decode($row->sbouy);
foreach($dv as $idx => $val){
$out[] = $val;
}
}
echo '<pre>';
print_r($out); // This is what you want :)
You have to define $out outside foreach. Instead of loop you can even use array_merge