How can set php array value in only one array - php

I have an array an add it in foreach loop my code is:
foreach($array as $a) {
echo var_dump($a);
}
and my output is:
how can set my output to this:
and then show count of each value in my array. how can set this?

Stony answer is good. But I realize you want to echo the length of the value that you have. So I just expanded Stony's answer.
$myarray = array();
foreach($array as $a) {
$myarray[] = $a;
}
foreach($myarray as $key => $value) {
echo "Length of $value at index $key is " . strlen($value) . " <br/> ";
}
Note that I use PHP function strlen to calcualate the length of the string. Hope this helps. Thank you.

Using FOR loop u can do this like
for($i=0;$i<=sizeof($array);$i++)
{
echo $i."=>".$array[$i]."(length=".sizeof($array[$i]).")";
}

Try this code,
$arr = array("value1", "value2", "value3", "value4");
$newArr = array();
foreach ($arr as $val) {
$newArr [] = "string '$val' (length=".strlen($val).")";
}
print_r($newArr);exit;
Expected output:
Array
(
[0] => string 'value1' (length=6)
[1] => string 'value2' (length=6)
[2] => string 'value3' (length=6)
[3] => string 'value4' (length=6)
)
Try Demo

Related

How to match string to an Array to get the value?

I have an array with corresponding value.
Array
(
[0] => BBsma=200
[1] => SMAperiod=300
[2] => SMA1=400
[3] => SMA2=500
[4] => EMAperiod=300
[5] => EMA1=24
[6] => EMA2=8
)
Now I want to match a certain string like for example BBsma that should return 200. Any help?
Got the array using these codes.
$txt = file_get_contents('INDICATORS.txt');
$rows = explode("\n", $txt);
array_shift($rows);
INDICATORS.txt content
BBperiod=100
BBsma=200
SMAperiod=300
SMA1=400
SMA2=500
EMAperiod=300
EMA1=24
EMA2=8
After you explode your text to the lines use this code:
for($i=0;$i<sizeof($rows);$i++)
{
$temp=explode("=",$rows[$i]);
if(sizeof($temp)==2)
{
$arr[$temp[0]]=$temp[1];
}
}
You will have named array in $arr
if you want to cast second part to int, you just change 6-line to this:
$arr[$temp[0]]=intval($temp[1]);
You could iterate over every line of your array and find the value with a regular match.
Code:
$txt = file_get_contents('INDICATORS.txt');
$rows = explode("\n", $txt);
/*
$rows = [
"BBsma=200",
"SMAperiod=300",
"SMA1=400",
"SMA2=500",
"EMAperiod=300",
"EMA1=24",
"EMA2=8",
];
*/
foreach ($rows as $k=>$v) {
if (preg_match("/(BBsma|SMAperiod|EMAperiod)=([0-9]+)/", $v, $matches)) {
echo "found value " . $matches[2] . " for entry " . $matches[1] . " in line " . $k . PHP_EOL;
}
}
Output:
found value 200 for entry BBsma in line 0
found value 300 for entry SMAperiod in line 1
found value 300 for entry EMAperiod in line 4
You can explode by new line as PHP_EOL like this
$col = "BBsma";
$val = "";
foreach(explode(PHP_EOL,$str) as $row){
$cols = explode("=",$row);
if(trim($cols[0]) == $col){
$val = $cols[1];
break;
}
}
echo "Value $col is : $val";
Live Demo
If your going to use the array a few times, it may be easier to read the file into an associative array in the first place...
$rows = [];
$file = "INDICATORS.txt";
$data = file($file, FILE_IGNORE_NEW_LINES);
foreach ( $data as $item ) {
$row = explode("=", $item);
$rows [$row[0]] = $row[1];
}
echo "EMA1 =".$rows['EMA1'];
This doesn't do the array_shift() but not sure why it's used, but easy to add back in.
This outputs...
EMA1 =24
I think that using array filter answers your question the best. It returns an array of strings with status code 200. If you wanted to have better control later on and sort / search through codes. I would recommend using array_walk to create some sort of multi dimensional array. Either solution will work.
<?php
$arr = [
"BBsma=200",
"SMAperiod=300",
"SMA1=400",
"SMA2=500",
"EMAperiod=300",
"EMA1=24",
"EMA2=8",
];
$filtered = array_filter($arr,"filter");
function filter($element) {
return strpos($element,"=200");
}
var_dump($filtered); // Returns array with all matching =200 codes: BBSMA=200
Output:
array (size=1)
0 => string 'BBsma=200' (length=9)
Should you want to do more I would recommend doing something like this:
///////// WALK The array for better control / manipulation
$walked = [];
array_walk($arr, function($item, $key) use (&$walked) {
list($key,$value) = explode("=", $item);
$walked[$key] = $value;
});
var_dump($walked);
This is going to give you an array with the parameter as the key and status code as it's value. I originally posted array_map but quickly realized array walk was a cleaner solution.
array (size=7)
'BBsma' => string '200' (length=3)
'SMAperiod' => string '300' (length=3)
'SMA1' => string '400' (length=3)
'SMA2' => string '500' (length=3)
'EMAperiod' => string '300' (length=3)
'EMA1' => string '24' (length=2)
'EMA2' => string '8' (length=1)
Working with the array becomes a lot easier this way:
echo $walked['BBsma']; // 200
$anything = array("BBsma"=>"200", "SMAperiod"=>"300", "SMA1"=>"400");
echo "the value is " . $anything['BBsma'];
This will return 200

How to separate the operator inside the array?

I did this from the database.
how to find the the $dependency separator after explode i want explode that array .
$dependency = 2/3&3/6;
$find = explode('&',$dependency);
string(7) "2/3&3/6"
I am getting like,
sarray(2) {
[0]=>string(3) "2/3"
[1]=>string(3) "3/6"
}
But i want the result to be like this:
sarray(2) {
[0]=>array(2) {
[0]=>string(1) "2"
[1]=>string(3) "3"
}
[1]=>array(2) {
[0]=>string(1) "3"
[1]=>string(3) "6"
}
}
please help to find the this array separator.
You need read the array using foreach then explode again to get the desired result.
$dependency = '2/3&3/6';
$find = explode('&',$dependency);
$result = array();
foreach($find as $val){
$result = array_merge($result,explode("/",$val));//Store all the values in one array
or
$result[]=explode("/",$val); //store array as key
}
var_dump($result);
Here you go first explode with '&' then with '/' on each array item
$str = "2/3&3/6";
$arr= explode('&',$str);
foreach($arr as $val){
$arrData[]= explode('/',$val);
}
echo "</pre>";
print_r($arrData);
You have to further use foreach to separate string again
$dependency = "2/3&3/6";
$find = explode('&',$dependency);
$new_array=array();
foreach ($find as $key => $value) {
$new_array[]=explode('/',$value);
}
var_dump($new_array);
OUTPUT:
array (size=2)
0 =>
array (size=2)
0 => string '2' (length=1)
1 => string '3' (length=1)
1 =>
array (size=2)
0 => string '3' (length=1)
1 => string '6' (length=1)

JSON arrays using PHP

I'm having an array "pollAnswers" which displays:
Array
(
[0] => Sachin
[1] => Dhoni
)
in PHP and I want it to display as:
"pollAnswers":[
{"pollAnswersID":0, "pollAnswer":"Sachin"},
{"pollAnswersID":1, "pollAnswer":"Dhoni"}
]
in JSON output.
I've tried using array_fill_keys and array_flip but that's not solution for this. It seems I need to split the array_keys and array_values and then do some concatenation to get this, but I'm stuck here!
Online check link
Try this
$arr = array("Sachin", "Dhoni");
$sub_arr = array();
$final = array();
foreach($arr as $key => $val){
$sub_arr['pollAnswersId'] = $key;
$sub_arr['pollAnswer'] = $val;
$sub_final[] = $sub_arr;
}
$final['pollAnswers'] = $sub_final;
echo json_encode($final);
result
{"pollAnswers":[
{"pollAnswersId":0,"pollAnswer":"Sachin"},
{"pollAnswersId":1,"pollAnswer":"Dhoni"}
]}
You can try with array_map.
$Array = array('Sachin', 'Dhoni');
$new = array_map(function($v, $k) {
return ['pollAnswersId' => $k, 'pollAnswer' => $v]; // return the sub-array
}, $Array, array_keys($Array)); // Pass the values & keys
var_dump(json_encode(array("pollAnswers" => $new)));
Output
"{"pollAnswers":[
{"pollAnswersId":0,"pollAnswer":"Sachin"},
{"pollAnswersId":1,"pollAnswer":"Dhoni"}
]}"
For older versions of PHP.
return array('pollAnswersId' => $k, 'pollAnswer' => $v);
Fiddle
<?php
$answerArray = [];
foreach($yourArray as $key => $r)
$answerArray[] = ['pollAnswersId' => $key, 'pollAnswer' => $r];
echo json_encode($answerArray);
Here you go.
Try this:
$givenArray = array("Sachin","Dhoni");
$answerArray = [];
foreach($givenArray as $key => $r)
$answerArray[] = ['pollAnswersId' => $key, 'pollAnswer' => $r];
echo $out = json_encode(array('pollAnswers' => $answerArray));

Get foreach numeric index when keys are named

This question is just for fun and out of curiosity.
Edit : My question is different than
How to find the foreach index
Because $key has already a non-numeric value in my case.
Without having a variable outside a foreach that is increment inside the foreach scope, as the usual $i, is there a way to get the index of an item when $key is already named ?
Exemples :
$myNumericIndexArray = ('foo', 'bar', 'go', 'habs');
foreach($myNumericIndexArray as $key => $value){
//Here $key will be 0 -> 1 -> 2 -> 3
}
Now, if I have :
$myNamedIndexArray = ('foo' => 'bar', 'go' => 'habs', 'CSGO_bestTeam' => 'fnatic');
foreach($myNamedIndexArray as $key => $value){
//Here $key will be foo -> go -> CSGO_bestTeam
}
Can I, without having to :
$i=0;
foreach($myNamedIndexArray as $key => $value){
//Here $key will be foo -> go -> CSGO_bestTeam
$i++;
}
access the index of a named array. Something declared in the foreach declaration like in a for or a status of $key ?
Have a good one.
If you really want index array of associative array than try this:
$myNamedIndexArray = ['foo' => 'bar', 'go' => 'habs', 'CSGO_bestTeam' => 'fnatic'];
$keys = array_keys($myNamedIndexArray);
foreach($myNamedIndexArray as $key => $value){
echo array_search($key, $keys);
}
I don't know why you would want to do an array_keys() and array_search() every loop iteration. Just build a reference array and you can still foreach() the original:
$positions = array_flip(array_keys($myNamedIndexArray));
foreach($myNamedIndexArray as $key => $value){
echo "{$key} => {$value} is position {$positions[$key]}\n";
}
Something like this :
<?php
$myNamedIndexArray = array('foo' => 'bar', 'go' => 'habs', 'CSGO_bestTeam' => 'fnatic');
$numericIndexArray = array_keys($myNamedIndexArray);
foreach($numericIndexArray as $key=>$value){
echo $key.'</br>'; //here key will be 0 1 2
echo $value. '</br>';
}
I'd try something like this:
<?php
$myNamedIndexedArray = ['foo' => 'bar', 'go' => 'habs', 'CSGO_bestTeam' => 'fnatic'];
$myNumberIndexedArray = array_keys($myNamedIndexedArray);
foreach($myNumberIndexedArray as $key => $value){
echo $key. " => " . $myNamedIndexedArray[$myNumberIndexedArray[$key]]."<br />";
}
?>
Adn the output will be:
0 => bar
1 => habs
2 => fnatic

converter array to key and value in array php

i have array look like this:
$arr=array(
'key1'=>'value1',
'key2'=>'value2',
0=>array(
'sub1_key1'=>'sub1_value1',
'sub1_key2'=>'sub1_value2',
),
'key3'=>array(
'sub2_key1'=>'sub2_value1',
'sub2_key2'=>'sub2_value2',
),
//....
);
how to converter array $arr to array look like this:
$arr=array(
'key1'=>'value1',
'key2'=>'value2',
'sub1_key1'=>'sub1_value1',
'sub1_key2'=>'sub1_value2',
'sub2_key1'=>'sub2_value1',
'sub2_key2'=>'sub2_value2',
//....
);
somebody can help me?
Try this out. This works for you hopefully.
This is not trivial, because you are going to reduce multi.dim. array to single one and also ignore the key of the first array.
I have tested the following code and it produces that result you have shown.
function ChangeArrayToSingleArray($array) {
if (!$array) return false;
$flat = array();
$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($array));
foreach ($iterator as $key=>$value)
$flat[$key] = $value;
return $flat;
}
var_dump(ChangeArrayToSingleArray($arr));
output is some thing like.
array (size=6)
'key1' => string 'value1' (length=6)
'key2' => string 'value2' (length=6)
'sub1_key1' => string 'sub1_value1' (length=11)
'sub1_key2' => string 'sub1_value2' (length=11)
'sub2_key1' => string 'sub2_value1' (length=11)
'sub2_key2' => string 'sub2_value2' (length=11)
$new = array();
foreach ($arr as $key => $value) {
if (is_array($value)) {
foreach ($value as $k => $v) { // having nested loop to save keys and values into new array
$new[$k] = $v;
}
} else {
$new[$key] = $value; // leaving values intact
}
}
print_r($new); // returns Array ( [key1] => value1 [key2] => value2 [sub1_key1] => sub1_value1 [sub1_key2] => sub1_value2 [sub2_key1] => sub2_value1 [sub2_key2] => sub2_value2 )
DEMO
Use array_walk () function that may help you http://au2.php.net/array_walk
you can try
function flatten($array) {
$new_array = array();
foreach ($array as $key => $value) {
if ( is_array($value) ) {
$new_array = array_merge ( $new_array, flatten($value));
} else {
$new_array[$key] = $value;
}
}
return $new_array;
}
then you can just call :
$flattened_array = flatten($arr);
in your case
this will work with any depth array as it works recursively
here's the php fiddle demo

Categories