Remove the [0] element from array without deleting whole array - php

I'm trying to make a script to remove any empty elements from my array.
However an empty element is in the [0] slot so when I unset the value it deletes my whole array. At least I think that's what's happening, why isn't this working?
<?php
$idfile = file_get_contents("datafile.dat");
$idArray = explode("\n", $idfile);
print_r($idArray);
foreach ($idArray as $key => &$value) {
echo "Key is: ".$key." and value is: ".$value."<br />\n";
if ($value == ""){
echo "Killing value of ".$value."<br />";
unset($value[$key]);
}
$value = str_replace("\n", "", $value);
$value = str_replace("\r", "", $value);
$value = $value.".dat";
}
print_r($idArray);
?>
Here's the output:
Array
(
[0] =>
[1] => test1
[2] => test2
)
Key is: 0 and value is: <br>
Killing value of <br>

If you are just removing an empty value try using unset($idArray[$key]) instead. If you are just trying to remove the first element overall, use array_shift()

Another nice solution would be to use the array_filter() method, which will handle the iteration and return the filtered array for you:
<?php
function isNotEmpty($str)
{
return strlen($str);
}
$idfile = file_get_contents("datafile.dat");
$idArray = explode("\n", $idfile);
$idArray = array_filter($idArray, "isNotEmpty");
?>

Related

Textarea lines to array using php

I have a php variable that contain value of textarea as below.
Name:Jay
Email:jayviru#demo.com
Contact:9876541230
Now I want this lines to in array as below.
Array
(
[Name] =>Jay
[Email] =>jayviru#demo.com
[Contact] =>9876541230
)
I tried below,but won't worked:-
$test=explode("<br />", $text);
print_r($test);
you can try this code using php built in PHP_EOL but there is little problem about array index so i am fixed it
<?php
$text = 'Name:Jay
Email:jayviru#demo.com
Contact:9876541230';
$array_data = explode(PHP_EOL, $text);
$final_data = array();
foreach ($array_data as $data){
$format_data = explode(':',$data);
$final_data[trim($format_data[0])] = trim($format_data[1]);
}
echo "<pre>";
print_r($final_data);
and output is :
Array
(
[Name] => Jay
[Email] => jayviru#demo.com
[Contact] => 9876541230
)
Easiest way to do :-
$textarea_array = array_map('trim',explode("\n", $textarea_value)); // to remove extra spaces from each value of array
print_r($textarea_array);
$final_array = array();
foreach($textarea_array as $textarea_arr){
$exploded_array = explode(':',$textarea_arr);
$final_array[trim($exploded_array[0])] = trim($exploded_array[1]);
}
print_r($final_array);
Output:- https://eval.in/846556
This also works for me.
$convert_to_array = explode('<br/>', $my_string);
for($i=0; $i < count($convert_to_array ); $i++)
{
$key_value = explode(':', $convert_to_array [$i]);
$end_array[$key_value [0]] = $key_value [1];
}
print_r($end_array); ?>
I think you need create 3 input:text, and parse them, because if you write down this value in text area can make a mistake, when write key. Otherwise split a string into an array, and after create new array where key will be odd value and the values will be even values old array

how to modify array_count_values output

i have an array
$array=(1,1,2,3,3,3,4);
i need to find each element how many times each element is exist in array .
So that i use
$occurences = array_count_values($array);
output is
Array
(
[1] => 2
[2] => 1
[3] => 3
[4] => 1
)
But i need to arrage the out put in following format
1 : 2
2 : 1
3 : 3
4 : 1
how can i do that ?
is there an other solution rater than using array_count_values
please help ;
Use foreach to iterate over every occurance and echo them out.
// If they are in wrong order, sort your array
ksort($occurences);
// Print output
if(count($occurences)>0){
foreach ($occurences as $key => $value) {
echo $key.' : '.$value.'<br />';
}
}
EDIT
To sort by no of occurances, use arsort.
arsort($occurences);
Of course, before printing it.
If 2:1 must come before 4:1 in your case, use:
asort($occurences);
arsort($occurences);
Just use this loop to have output like you need
foreach ($occurences as $k => $v) {
echo "$k : $v <br>";
}
You can use json_encode or array_keys and array_values
<?php
$array= array(1,1,2,3,3,3,4);
$occurences = array_count_values($array);
$array_keys = array_keys($occurences);
$array_values = array_values($occurences);
for($i=0; $i<count($array_keys); $i++) {
echo $array_keys[$i].':'.$array_values[$i].'\n';//add \n or \br tag
}
//you can echo json_encode
echo json_encode($occurences);

How to extract all 2nd level values (leaf nodes) from a 2-dimensional array and join with commas?

How can I get the list of values from my array:
[data] => Array
(
[5] => Array
(
[0] => 19
[1] => 18
[2] => 20
)
[6] => Array
(
[0] => 28
)
)
Expected output result string will be: 19,18,20,28
Thanks!
With one line, no loop.
echo implode(',', call_user_func_array('array_merge', $data));
Try it here.
Use following php code:
$temp = array();
foreach($data as $k=>$v){
if(is_array($v)){
foreach($v as $key=>$value){
$temp[] = $value;
}
}
}
echo implode(',',$temp);
Use following code.
$string = '';
foreach($yourarray as $k){
foreach($k as $l){
$string. = $l.",";
}
}
Just loop over sub arrays. Store values to $result array and then implode with ,
$result = array();
foreach ($data as $subArray) {
foreach ($subArray as $value) {
$result[] = $value;
}
}
echo implode(',', $result);
$data = array(5 => array(19,18,20), 6 => array(28));
foreach ($data as $array) {
foreach ($array as $array1) {
echo $array1.'<br>';
}
}
Try this one. It will help you
Since all of the data that you wish to target are "leaf nodes", array_walk_recursive() is a handy function to call.
Code: (Demo)
$data=[5=>[19,18,20],6=>[28]];
array_walk_recursive($data,function($v){static $first; echo $first.$v; $first=',';});
Output:
19,18,20,28
This method uses a static declaration to avoid the implode call and just iterates the call of echo with preceding commas after the first iteration. (no temporary array generated)
I haven't really taken the time to consider any fringe cases, but this is an unorthodox method that will directly provide the desired output string without loops or even generating a new, temporary array. It's a tidy little one-liner with a bit of regex magic. (Regex Demo) It effectively removes all square & curly brackets and double-quoted keys with trailing colons.
Code: (Demo)
$data=[5=>[19,18,20],6=>[28]];
echo preg_replace('/[{}[\]]+|"\d+":/','',json_encode($data));
Output:
19,18,20,28
To be clear/honest, this is a bit of hacky solution, but I think it is good for SO researchers to see that there are often multiple ways to achieve any given outcome.
try with this..
foreach($data as $dataArr){
foreach ($subArray as $value) {
$res[] = $value;
}
}
echo implode(',', $res);
Just use nested foreach Statements
$values = array();
foreach($dataArray as $key => $subDataArray) {
foreach($subDataArray as $value) {
$values[] = $value;
}
}
$valueString = implode(',', $values);
Edit: Added full solution..

PHP replace Array values based on certain requirements

I have an array as such:
$array = ["1","0","0","1","1"]
//replace with
$newArray = ["honda","toyota","mercedes","bmw","chevy"]
// only if the original array had a value of "1".
// for example this is my final desired output:
$newArray = ["honda","0","0","bmw","chevy"]
I want to change each value in a specific order IF and only if the array value is equal to "1".
For example the values, "honda", "toyota", "mercedes", "bmw", "chevy" should only replace the array values if the value is "1" otherwise do not replace it and they must be in the right position for example the first element in the array must only be changed to honda, not toyota or any of the other values.
I know I must iterate through the array and provide an if statement as such:
foreach($array as $val) {
if($val == 1){
//do something
} else {
return null;
}
}
Please guide me in the right direction and describe how to replace the values in order, so that toyota cannot replace the first array value only the second position.
You can so something like this - iterating over the array by reference and replacing when the value is 1 (string) and the value in the replace array exists:
foreach($array as $key => &$current) {
if($current === '1' && isset($replace[$key]))
$current = $replace[$key];
}
Output:
Array
(
[0] => honda
[1] => 0
[2] => 0
[3] => bmw
[4] => chevy
)
As per your comment, to output an imploded list of the cars that do have values, you can do something like this - filtering out all zero values and imploding with commas:
echo implode(
// delimiter
', ',
// callback - filter out anything that is "0"
array_filter($array, function($a) {
return $a != '0';
})
);
Currently, our if is asking if $val is true (or if it exists) while your numeric array's values are strings.
Try this:
$array = ["1","0","0","1","1"]
$newArray = ["honda","toyota","mercedes","bmw","chevy"]
foreach($array as $key => $val) {
if($val === '1'){ // if you only want honda
$array[$key] = $newArray[$key];
} else {
return null;
}
}
PHP Code
$array = array("1","0","0","1","1");
$newArray = array("honda","toyota","mercedes","bmw","chevy");
foreach($array as $key => $val) {
if($val === '1')
$array[$key] = $newArray[$key];
}
Would produce the answer you're looking for

PHP array does not sort at all

I have a problem with sorting of an array.
$infoGroup is the result of a 'ldap_get_entries' call earlier. As I step through this array I put the result in the array $names.
Then I want to sort $names in alfabetical order, I have tried a number of different methods but to no avail. The array always stays in the same order it was constructed.
What have I missed?
foreach($infoGroup[$i]['member'] as $member) {
//echo "<li>".$member;
$go = stripos($member, "n");
unset($names);
$ai++;
if ( $go == 1 ) {
// extract member name from string
$temp = substr($member, 0, stripos($member, ","));
// Strip the CN= and change to lowercase for easy handling
$temp = str_replace("cn=", "", $temp);
$names[$ai] = ($temp);
}
if (natsort($names)){
foreach ($names as $key => $val) {
echo "<li>";
echo "$key $val";
}
}
}
$ai = 0;
This is the result however I try to sort the $names array:
Henrik Lindbom
Klaus Rödel
Admin
Bernd Brandstetter
proxyuser
Patrik Löfström
Andreas Galic
Martin Stalder
Hmmm.. a bit hard to explain, but the issue is because you are sorting your array inside that foreach() loop. Essentially, since you are creating the array element in the iteration of the first loop, the natsort() only has 1 element to sort and your nested foreach() loop is only outputting that 1 element, which is then unset() at the second and further iterations...
Extract that second foreach() that sorts and outputs and remove the unset() from the top of the first loop. This should output your desired results.
Something like this...
foreach($infoGroup[$i]['member'] as $member) {
//echo "<li>".$member;
$go = stripos($member, "n");
$ai++;
if ( $go == 1 ) {
// extract member name from string
$temp = substr($member, 0, stripos($member, ","));
// Strip the CN= and change to lowercase for easy handling
$temp = str_replace("cn=", "", $temp);
$names[$ai] = ($temp);
}
}
if (natsort($names)){
foreach ($names as $key => $val) {
echo "<li>";
echo "$key $val";
}
}
$ai = 0;

Categories