Saturday 20 August 2022

Write Smart code in PHP arrays using in built functions.

We have a requirement to fetch data from database and display user names and their salaries.

Output required:

Morgan's salary: 6000, Jermy's salary: 5500, Phil's salary: 5500, Anthony's salary: 5500, John's salary: 5500, Norman's salary: 5500

There are 2 ways of doing this that generate the same result.

<?php

$databseArray = [];

$databseArray[] = [1, 'Morgan', 6000];

$databseArray[] = [2, 'Jermy', 5500];

$databseArray[] = [3, 'Phil', 5500];

$databseArray[] = [4, 'Anthony', 5500];

$databseArray[] = [5, 'John', 5500];

$databseArray[] = [6, 'Norman', 5500];


echo 'Approach 1';

echo '<br/>';

if (! empty($databseArray)) {

 $str = '';

 $cntr = 0;

 $len = count($databseArray);

 foreach ($databseArray as $databseRow) {

  $str .= ' '.$databseRow[1] ."'s". ' salary: '.$databseRow[2];

  if ($cntr < ($len-1))

  $str .= ', ';

  ++$cntr;

 }

}

echo $str;

echo '<br/>--------------------------------------------------------------<br/>';

echo 'Approach 2';

echo '<br/>';

$outputArr = [];

if (! empty($databseArray)) {

 foreach ($databseArray as $databseRow) {

  $outputArr[] = ' '.$databseRow[1] ."'s". ' salary: '.$databseRow[2];

 }

}

echo implode(', ', $outputArr);

Friday 19 August 2022

Design Pattern in PHP

<?php

class Booklibrary {

 private $bookName = '';

 private $bookAuthor = '';

 const BR = '<br/>';

 public function __construct($name = '', $author = '') {

  $this->bookName = $name;

  $this->bookAuthor = $author;

 }

 public function getNameAndAuthor() {

  return $this->bookName . ' - ' . $this->bookAuthor . self::BR;

 }

}

class BooklibraryFactory {

 public static function create($name, $author) {

  return new Booklibrary($name, $author);

 }

}

$bookOne = BooklibraryFactory::create('Shiv Khera', 'You can win');

$bookTwo = BooklibraryFactory::create('Norman Vincent Peale', 'The Power Of Positive Thinking.');


echo $bookOne->getNameAndAuthor();

echo $bookTwo->getNameAndAuthor();

Monday 15 August 2022

ReactJS useState() method explained

 The ReactJS useState() method is used to save and set state variables in the React Components.

For this to use, we need to import useState() from React.

The useState() method returns an array.

It has two parameters:

1) state variable

2) function to change state variable.


For example:


const [count, setCount] = useState(0);

Here we are destructing the useState() array with two variables.

the count is variable and setCount is a method.

// Import useState from React

import {useState} from 'react';


function App() {

 const [count, setCount] = useState(0);

}


We can set the count using setCount() method.

Parenting tips to inculcate learning habits in your kid

Parenting tips to inculcate learning habits in your kid Tip #1) Children do not learn things, they emitate. So, try to do things by yours...