Showing posts with label PHP var_dump. Show all posts
Showing posts with label PHP var_dump. Show all posts

Friday, 2 August 2019

Thursday, 30 August 2018

PHP extracts multidimensional associative array keys as text


With a basic associative array like:


$ar = array("First" => 1, "Second" , "Third" =>"Three");

if you do:
foreach($ar as $key => $val) {

  var_dump($key);

}

This will produce:
string 'First' (length=5)

int 0

string 'Third' (length=5)

How do you Achieve the same results in a Multidimensional Array?
Something like:
array( 0 => array(
            "First" => 1, "Two", "Third" => "Three"
                )
     );

I tried:
foreach($ar as $k => $v){

        var_dump($ar[0][$k]);
        }

I got:
string 'Two' (length=3)

Instead of:
string 'First' (length=5)

    int 0

    string 'Third' (length=5)

Thanx

If $ar is equal to this:
array( 0 => array(
        "First" => 1, "Two", "Third" => "Three"
            )
 );

You could iterate over the inner array to get the same result:
foreach ($ar as $k => $v) {
    foreach ($v as $k2 => $v2) {
            var_dump($k2);
    }
}

Output:
string(5) "First"
  int(0)
string(5) "Third"

PHP - Create an associative array from the .txt file


This question already has an answer here:


  • CSV to Associative Array 5 answers
I have .txt file formatted as such:
    "id","dealer_id","vin","stockno",
    "1","2","3","4",
    "5","6","7","8",
    "9","10","11",12"

My goal is push this into an associative array like such:
    "id"=>"1", "dealer_id"=>"2", "vin"=>"3", "stockno"=>"4"

My question is, the data loops through for every 4 entries. In the example above, I should have 3 arrays created like such:
    "id"=>"1", "dealer_id"=>"2", "vin"=>"3", "stockno"=>"4"
    "id"=>"5", "dealer_id"=>"6", "vin"=>"7", "stockno"=>"8"
    "id"=>"9", "dealer_id"=>"10", "vin"=>"11", "stockno"=>"12"

How can I make this happen within PHP -- if possible at all?

Here's one approach:
<?php
$file = fopen('data.txt', 'r');
$headers = fgetcsv($file);
$result = array();
while ($row = fgetcsv($file)) {
        if (!$row[0]) continue;
        $nextItem = array();
        for ($i = 0; $i < 4; ++$i) {
                $nextItem[$headers[$i]] = $row[$i];
        }
        $result[] = $nextItem;
}
fclose($file);
var_dump($result);

This uses fgetcsv to read each delimited row of the file. The first row is used as the header names. Then, for each other row, we create a new entry and match the indexes to the header names. I set it to 4 because you have a trailing delimiter that creates an empty entry at the end, if you removed those from the input you could use the length of $headers for the inner loop.
Here is the result of the var_dump for your data:
array(3) {
  [0]=>
  array(4) {
    ["id"]=>
    string(1) "1"
    ["dealer_id"]=>
    string(1) "2"
    ["vin"]=>
    string(1) "3"
    ["stockno"]=>
    string(1) "4"
  }
  [1]=>
  array(4) {
    ["id"]=>
    string(1) "5"
    ["dealer_id"]=>
    string(1) "6"
    ["vin"]=>
    string(1) "7"
    ["stockno"]=>
    string(1) "8"
  }
  [2]=>
  array(4) {
    ["id"]=>
    string(1) "9"
    ["dealer_id"]=>
    string(2) "10"
    ["vin"]=>
    string(2) "11"
    ["stockno"]=>
    string(3) "12""
  }
}

PHP: Sort set based on another table


 I have visited similar question here but not getting what i want in php. Suppose i have 2 arrays. All checking should be case insensitive. say Field0 is same as field0 or fiEld1 is same as Field1.


array1 is array(
"0"=>"field0",
"1"=>"field1",
"2"=>"field2",
"3"=>"field3",
);

array2 is array(
"0"=>"field3",
"1"=>"field2",
"2"=>"field0",
"3"=>"field1",
"4"=>"field6",
"5"=>"field5",
);

Now I want array2 to be sorted based on array1 like the following:
array2 is array(
"0"=>"field0",
"1"=>"field1",
"2"=>"field2",
"3"=>"field3",
"4"=>"field6",
"5"=>"field5",
);

look here array1 has 4 elements so array2 should be sorted based exactly 4 elements of array1 and rest 2 element (index 4,5 of array2) should as it is in array2 before.

Try array_intersect combined with array_diff:
<?php
$array1 = array(
    "0"=>"field0",
    "1"=>"field1",
    "2"=>"field2",
    "3"=>"field3",
);

$array2 = array(
    "0"=>"field3",
    "1"=>"field2",
    "2"=>"field0",
    "3"=>"field1",
    "4"=>"field6",
    "5"=>"field5",
);

$array3 = array_merge(
    array_intersect($array1, $array2),
    array_diff($array2, $array1)
);

var_dump($array3);

Update
For a case insensitive approach, use array_map to guarantee all entries in both arrays are lower-cased:
$array3 = array_map('strtolower', $array1);
$array4 = array_map('strtolower', $array2);

$array5 = array_merge(
    array_intersect($array3, $array4),
    array_diff($array4, $array3)
);

var_dump($array5);

Tuesday, 2 June 2015

Friday, 3 October 2014

is_null in PHP

is_null — Finds whether a variable is NULL


Syntax: 
bool is_null ( mixed $var )

Finds whether the given variable is NULL.
Parameters: 

var

    The variable being evaluated.

Return Values:

Returns TRUE if var is null, FALSE otherwise.
Examples:

Example #1 is_null() example
<?php

error_reporting(E_ALL);

$foo = NULL;
var_dump(is_null($inexistent), is_null($foo));

?>

Notice: Undefined variable: inexistent in ...
bool(true)
bool(true)

var_dump in PHP

var_dump — Dumps information about a variable

Syntax: 
void var_dump ( mixed $expression [, mixed $... ] )

This function displays structured information about one or more expressions that includes its type and value. Arrays and objects are explored recursively with values indented to show structure.

All public, private and protected properties of objects will be returned in the output unless the object implements a __debugInfo() method (implemented in PHP 5.6.0).
Tip

As with anything that outputs its result directly to the browser, the output-control functions can be used to capture the output of this function, and save it in a string (for example).
Parameters: 

expression

    The variable you want to dump.

Return Values:

No value is returned.
Examples:

Example #1 var_dump() example
<?php
$a = array(1, 2, array("a", "b", "c"));
var_dump($a);
?>

The above example will output:

array(3) {
  [0]=>
  int(1)
  [1]=>
  int(2)
  [2]=>
  array(3) {
    [0]=>
    string(1) "a"
    [1]=>
    string(1) "b"
    [2]=>
    string(1) "c"
  }
}

<?php

$b = 3.1;
$c = true;
var_dump($b, $c);

?>

The above example will output:

float(3.1)
bool(true)

is_int in PHP

is_int — Find whether the type of a variable is integer

Syntax: bool is_int ( mixed $var )
Finds whether the type of the given variable is integer.
Note:To test if a variable is a number or a numeric string (such as form input, which is always a string), you must use is_numeric().

Parameters: 
var:The variable being evaluated.
Return Values:
Returns TRUE if var is an integer, FALSE otherwise.
Example #1
<?php
$values = array(23, "23", 23.5, "23.5", null, true, false);
foreach ($values as $value) {
    echo "is_int(";
    var_export($value);
    echo ") = ";
    var_dump(is_int($value));
}
?>

The above example will output:

is_int(23) = bool(true)
is_int('23') = bool(false)
is_int(23.5) = bool(false)
is_int('23.5') = bool(false)
is_int(NULL) = bool(false)
is_int(true) = bool(false)
is_int(false) = bool(false)


is_integer — Alias of is_int
is_long — Alias of is_int

empty in PHP

empty — Determine whether a variable is empty

Syntax:
bool empty ( mixed $var )
Description:
Determine whether a variable is considered to be empty. 
       A variable is considered empty if it does not exist or if its value equals FALSE. 
        empty() does not generate a warning if the variable does not exist.
Parameter: var
    Variable to be checked
Note:
        Prior to PHP 5.5, empty() only supports variables; anything else will result in a parse error. 
        In other words, the following will not work: empty(trim($name)). 
        Instead, use trim($name) == false.
    No warning is generated if the variable does not exist. 
        That means empty() is essentially the concise equivalent to !isset($var) || $var == false.
Return Values:
Returns FALSE if var exists and has a non-empty, non-zero value. Otherwise returns TRUE.

The following things are considered to be empty:
        "" (an empty string)
        0 (0 as an integer)
        0.0 (0 as a float)
        "0" (0 as a string)
        NULL
        FALSE
        array() (an empty array)
        $var; (a variable declared, but without a value)

Changelog:
Version Description
5.5.0 empty() now supports expressions, rather than only variables.
5.4.0 Checking non-numeric offsets of strings returns TRUE.
Examples:

Example #1 A simple empty() / isset() comparison.
<?php
$var = 0;
// Evaluates to true because $var is empty
if (empty($var)) {
    echo '$var is either 0, empty, or not set at all';
}

// Evaluates as true because $var is set
if (isset($var)) {
    echo '$var is set even though it is empty';
}
?>

Example #2 empty() on String Offsets

PHP 5.4 changes how empty() behaves when passed string offsets.
<?php
$expected_array_got_string = 'somestring';
var_dump(empty($expected_array_got_string['some_key']));
var_dump(empty($expected_array_got_string[0]));
var_dump(empty($expected_array_got_string['0']));
var_dump(empty($expected_array_got_string[0.5]));
var_dump(empty($expected_array_got_string['0.5']));
var_dump(empty($expected_array_got_string['0 Mostel']));
?>

Output of the above example in PHP 5.3:

bool(false)
bool(false)
bool(false)
bool(false)
bool(false)
bool(false)

Output of the above example in PHP 5.4:

bool(true)
bool(false)
bool(false)
bool(false)
bool(true)
bool(true)

Monday, 29 September 2014

sscanf in PHP

PHP sscanf() function is utilized to parse a string according to specific format.
In PHP sscanf() function, the information will be returned as a array, If just two parameters are passed. 
In PHP sscanf() function, the information parsed are saved in them., if optional parameters are passed.

Syntax:

sscanf(string,format,arg1,arg2,arg++)
string : Required. Defines the input string being parsed.   

format : Required. Defines the format to use

arg1 : Optional. The first variable to store data in

arg2 : Optional. The second variable to store data in

arg++ : Optional. The third, forth, and so on, to store data in

Example:

<?php
$input_str = "Marks : Math – 88 :: Language - 75";
sscanf( $input_str,"Marks : Math - %d :: Language - %d", $math, $language);
var_dump($math, $language);
?>
Output will be:
int 88
int 75

Thursday, 4 September 2014

How to delete an element from an array in php?

When deleting an element from an array in PHP, a good function to use is the unset function. Here is an example of its usage:

An example of using unset to delete an element from an array:

$anArray = array("X", "Y", "Z");

unset($anArray[0]);

//'dumps' the content of $anArray to the page:
var_dump($anArray);  

The output of the var_dump function will be:
array(2) { [1]=> string(1) "Y" [2]=> string(1) "Z" }

Unset leaves all of the index values the same after an element is deleted


In our example above, the $anArray array will have values of “Y” and “Z” at indices of 1 and 2, respectively, after the element “X” is deleted using the unset function. This means that the indices for the other elements were not changed to adjust for the fact that the very first element (“X”) was deleted.
This would also mean that if you delete an element in the very middle of an array using unset then it would leave a gap in that array. Suppose we have this code:
$anArray = array("V", "W", "X", "Y", "Z");

unset($anArray[2]);

//'dumps' the content of $anArray to the page:
var_dump($anArray);  

This would output the following:
array(4) { [0]=> string(1) "V" [1]=> string(1) "W" 
[3]=> string(1) "Y" [4]=> string(1) "Z" }
Note in the output above, there is now no index # 2 – there is 0, 1, 3, and 4. Not having the continuous index values could potentially be a negative drawback. So what are you alternatives? Well, you could use a function called array_splice instead.

Using array_splice to delete an element from an array

The array_splice function is used to take one part of an array and replace it with some other contents. It can also be used to delete an element in an array. Here is an example and explanation of how to use array_splice to delete an element:
$anArray = array("V", "W", "X", "Y", "Z");

/*The 2 represents the offset - which basically
means move 2 positions from the  beginning of the
array and that will take us to the "X" element.  The 1 
represents the length of the array that you want to 
delete.  Since we just want to delete 1 element, we
set the length parameter to 1.

And, since we are not replacing that element with anything
- we do just want to delete it - we leave the 4th parameter (
which is optional) blank
*/

array_splice($anArray, 2, 1);
var_dump($anArray);
Running the code above will return us this:
array(4) { [0]=> string(1) "V" [1]=> string(1) "W"
[2]=> string(1) "Y" [3]=> string(1) "Z" }
So, using array_splice will set the index values back to their correct order, and we will be good to go again. There is however an assumption here that we should point out – the array_splice function accepts a value for the offset, not the index. Theoffset that we used in the example above happened to be equal to the index value. This is the case when the array we are dealing with already has a continuous integer index value, but if the array has been changed for whatever reason before array_splice is used, that may not always be the case.

Using the array_values and unset functions to delete an element from an array

If you use the array_values function right after the unset function, then you can set the index values back to their normal values, without any gaps in between the numbers. An example will help clarify:

Example of using array_values and unset to delete an element from an array:

$anArray = array("V", "W", "X", "Y", "Z");

/*
This will cause index 2 to go missing,
so the array indices of $anArray will be
0,1,3,4 - obviously the 2 is missing
*/

unset($anArray[2]);

/*
array_values will take an array as an input
and then take the array values (not the keys,
but just the values), and numerically index those values
into a new array.

This means that array_values will essentially re-index
the array that is given as an input, which restores the indices
to the correct order of 0,1,2, and 3:
*/

$anArray = array_values($anArray);

//'dumps' the content of $anArray to the page:
var_dump($anArray);  
This will now output:
array(4) { [0]=> string(1) "V" [1]=> string(1) "W" 
[2]=> string(1) "Y" [3]=> string(1) "Z" }

The array_values function will replace non-numeric key indices with numeric values

One thing we should point out about the array_values function is that if the key’s are non-numeric then they will be replaced with numeric values anyways. So, if you have an array that uses strings as indices (which is basically a hashtable), then array_values will remove those strings and replace them with numerical values. This is something you should definitely watch out for if you do decide to use the array_values function.
Now you have seen the different options that you have available to you when deleting an element from an array in PHP. And you are also aware of any potential side effects – which method you choose to use is entirely up to you.

How to delete an element in an array if you only know the value in PHP

You may want to delete an element in an array for which you only know the value (but not the corresponding key). In that scenario, you will have to search the array for the value you want first in order to get the corresponding key. You can use the array_search function to do that – it will simply take the array you want to search along with the value you want to search for as the parameters, and will return the corresponding key if it is found. Then, you can use the unset function to remove the element as before.
And finally, here is an example of how to do it:

An example of deleting an element in an array if you only know the value in PHP

$key = array_search($valueToSearch,$arrayToSearch);
if($key!==false){
    unset($array[$key]);
}